package com.dataaccess.dataaccess.web.service;


import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.dataaccess.dataaccess.common.base.BaseService;
import com.dataaccess.dataaccess.model.*;
import com.dataaccess.dataaccess.support.annotaion.Len;
import com.dataaccess.dataaccess.support.model.RespEntity;
import com.dataaccess.dataaccess.support.mybatisplus.QueryWrapper;
import com.dataaccess.dataaccess.support.utils.ByteUtil;
import com.dataaccess.dataaccess.support.utils.DateUtils;
import com.dataaccess.dataaccess.support.utils.HexUtils;
import com.dataaccess.dataaccess.support.utils.MyLogger;
import com.dataaccess.dataaccess.support.utils.https.StringUtil;
import com.dataaccess.dataaccess.web.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.dataaccess.dataaccess.support.utils.ByteUtil.getCRC;
import static com.dataaccess.dataaccess.support.utils.ByteUtil.hex2byte;
import static com.dataaccess.dataaccess.support.utils.DateUtils.contextLoads;

@Service
@Slf4j
public class DeviceAboatElectricService extends BaseService {

    @Resource
    public MyLogger logger;

    @Resource
    ElectricfireAlarmDeviceDataChangedMapper electricfireAlarmDeviceDataChangedMapper;
    @Resource
    ElectricfireNormalDeviceDataChangedMapper electricfireNormalDeviceDataChangedMapper;
    @Resource
    ElectricfireOtherDeviceDataChangedMapper electricfireOtherDeviceDataChangedMapper;
    @Resource
    ElectricfireOtherNormalDeviceDataChangedMapper electricfireOtherNormalDeviceDataChangedMapper;
    @Resource
    AlarmRecordMapper alarmRecordMapper;
    @Resource
    AlarmInNormalRecordMapper alarmInNormalRecordMapper;
    @Resource
    private AsyncService asyncService;
    @Resource
    private AlarmAllDeviceDataChangedMapper alarmAllDeviceDataChangedMapper;
    /**
     * 订阅--调用相关接口
     *
     * @param
     * @return
     */
    public RespEntity getInfo(JSONObject jsonParam) {

        return RespEntity.success();
    }

    /**
     * 回调地址--设备信息变化，订阅后推送设备信息变化通知
     *
     * @param
     * @return
     */
    public RespEntity deviceInfoChanged(JSONObject jsonParam) {

        return RespEntity.success();
    }

    public String getFireAlarmStr(JSONObject stringa, String sValue, String rValue) {
        String returnStr = "";
        if (stringa != null) {
            Set<String> set = stringa.keySet();
            if (sValue != null && StrUtil.isNotBlank(sValue) && sValue.equals("2")) {
                if (set.contains("L1")) {
                    returnStr = "漏电报警";
                } else if (set.contains("U1") && set.contains("l")) {
                    returnStr = "A相欠压报警";
                } else if (set.contains("U1")) {
                    returnStr = "A相过压报警";
                } else if (set.contains("U2") && set.contains("l")) {
                    returnStr = "B相欠压报警";
                } else if (set.contains("U2")) {
                    returnStr = "B相过压报警";
                } else if (set.contains("U3") && set.contains("l")) {
                    returnStr = "C相欠压报警";
                } else if (set.contains("U3")) {
                    returnStr = "C相过压报警";
                } else if (set.contains("T1")) {
                    returnStr = "温度A报警";
                } else if (set.contains("T2")) {
                    returnStr = "温度B报警";
                } else if (set.contains("T3")) {
                    returnStr = "温度C报警";
                } else if (set.contains("T4")) {
                    returnStr = "温度N报警";
                } else if (set.contains("I1")) {
                    returnStr = "电流A过载";
                } else if (set.contains("I2")) {
                    returnStr = "电流B过载";
                } else if (set.contains("I3")) {
                    returnStr = "电流C过载";
                }
            } else if (sValue != null && StrUtil.isNotBlank(sValue) && sValue.equals("3")) {
                if (set.contains("L1")) {
                    returnStr = "漏电恢复正常";
                } else if (set.contains("U1")) {
                    returnStr = "电压A恢复正常";
                }
                if (set.contains("U2")) {
                    returnStr = "电压B恢复正常";
                }
                if (set.contains("U3")) {
                    returnStr = "电压C恢复正常";
                } else if (set.contains("T1")) {
                    returnStr = "温度A恢复正常";
                } else if (set.contains("T2")) {
                    returnStr = "温度B恢复正常";
                } else if (set.contains("T3")) {
                    returnStr = "温度C恢复正常";
                } else if (set.contains("T4")) {
                    returnStr = "温度N恢复正常";
                } else if (set.contains("I1")) {
                    returnStr = "电流A恢复正常";
                } else if (set.contains("I2")) {
                    returnStr = "电流B恢复正常";
                } else if (set.contains("I3")) {
                    returnStr = "电流C恢复正常";
                }
            }
            if (StrUtil.isNotBlank(returnStr)) returnStr = returnStr + ";;" + getCode(returnStr) + ";;" + rValue;
        }
        return returnStr;
    }

    public boolean isAlarm(JSONObject stringa, String sValue, String rValue, JSONObject number) {
        String returnStr = "";
        boolean isAlarm = false;
        //检测项数值
        Map<String, String> itemMap = getItme(number);
        if (itemMap.isEmpty()) {
            return isAlarm;
        }
        if (stringa != null) {
            Set<String> set = stringa.keySet();
            if (sValue != null && StrUtil.isNotBlank(sValue) && sValue.equals("2")) {
                if (set.contains("L1")) {
                    returnStr = "漏电报警";
                    if (Double.parseDouble(rValue) >= Double.parseDouble(itemMap.get("漏电报警;max"))) {
                        isAlarm = true;
                    }
                } else if (set.contains("U1") && set.contains("l")) {
                    returnStr = "A相欠压报警";
                    if (Double.parseDouble(rValue) <= Double.parseDouble(itemMap.get("电压报警;min"))) isAlarm = true;
                } else if (set.contains("U1")) {
                    returnStr = "A相过压报警";
                    if (Double.parseDouble(rValue) >= Double.parseDouble(itemMap.get("电压报警;max"))) isAlarm = true;
                } else if (set.contains("U2") && set.contains("l")) {
                    returnStr = "B相欠压报警";
                    if (Double.parseDouble(rValue) <= Double.parseDouble(itemMap.get("电压报警;min"))) isAlarm = true;
                } else if (set.contains("U2")) {
                    returnStr = "B相过压报警";
                    if (Double.parseDouble(rValue) >= Double.parseDouble(itemMap.get("电压报警;max"))) isAlarm = true;
                } else if (set.contains("U3") && set.contains("l")) {
                    returnStr = "C相欠压报警";
                    if (Double.parseDouble(rValue) <= Double.parseDouble(itemMap.get("电压报警;min"))) isAlarm = true;
                } else if (set.contains("U3")) {
                    returnStr = "C相过压报警";
                    if (Double.parseDouble(rValue) >= Double.parseDouble(itemMap.get("电压报警;max"))) isAlarm = true;
                } else if (set.contains("T1")) {
                    if (Double.parseDouble(rValue) >= Double.parseDouble(itemMap.get("温度报警;max"))) isAlarm = true;
                    returnStr = "温度A报警";
                } else if (set.contains("T2")) {
                    if (Double.parseDouble(rValue) >= Double.parseDouble(itemMap.get("温度报警;max"))) isAlarm = true;
                    returnStr = "温度B报警";
                } else if (set.contains("T3")) {
                    if (Double.parseDouble(rValue) >= Double.parseDouble(itemMap.get("温度报警;max"))) isAlarm = true;
                    returnStr = "温度C报警";
                } else if (set.contains("T4")) {
                    returnStr = "温度N报警";
                    if (Double.parseDouble(rValue) >= Double.parseDouble(itemMap.get("温度报警;max"))) isAlarm = true;
                } else if (set.contains("I1")) {
                    returnStr = "电流A过载";
                    isAlarm = true;
                } else if (set.contains("I2")) {
                    returnStr = "电流B过载";
                    isAlarm = true;
                } else if (set.contains("I3")) {
                    returnStr = "电流C过载";
                    isAlarm = true;
                }
            } else if (sValue != null && StrUtil.isNotBlank(sValue) && sValue.equals("3")) {
                isAlarm = true;
                if (set.contains("L1")) {
                    returnStr = "漏电恢复正常";
                } else if (set.contains("U1")) {
                    returnStr = "电压A恢复正常";
                }
                if (set.contains("U2")) {
                    returnStr = "电压B恢复正常";
                }
                if (set.contains("U3")) {
                    returnStr = "电压C恢复正常";
                } else if (set.contains("T1")) {
                    returnStr = "温度A恢复正常";
                } else if (set.contains("T2")) {
                    returnStr = "温度B恢复正常";
                } else if (set.contains("T3")) {
                    returnStr = "温度C恢复正常";
                } else if (set.contains("T4")) {
                    returnStr = "温度N恢复正常";
                } else if (set.contains("I1")) {
                    returnStr = "电流A恢复正常";
                } else if (set.contains("I2")) {
                    returnStr = "电流B恢复正常";
                } else if (set.contains("I3")) {
                    returnStr = "电流C恢复正常";
                }
            }
            if (StrUtil.isNotBlank(returnStr)) returnStr = returnStr + ";;" + getCode(returnStr) + ";;" + rValue;
        }
        return isAlarm;
    }

    public String getCode(String name) {
        Map<String, String> map = new HashMap<>();
        //报警数据
        map.put("漏电报警", "2001");
        map.put("A 相欠压报警", "2002");
        map.put("A 相过压报警", "2003");
        map.put("B 相过压报警", "2004");
        map.put("B 相欠压报警", "2005");
        map.put("C 相欠压报警", "2006");
        map.put("C 相过压报警", "2007");
        map.put("温度 A 报警", "2008");
        map.put("温度 B 报警", "2009");
        map.put("温度 C 报警", "2010");
        map.put("温度 N 报警", "2011");
        map.put("电流 A 过载", "2012");
        map.put("电流 B 过载", "2013");
        map.put("电流 C 过载", "2014");
        //正常数据
        map.put("漏电恢复正常", "4001");
        map.put("电压 A 恢复正常", "4002");
        map.put("电压 B 恢复正常", "4003");
        map.put("电压 C 恢复正常", "4004");
        map.put("温度 A 恢复正常", "4005");
        map.put("温度 B 恢复正常", "4006");
        map.put("温度 C 恢复正常", "4007");
        map.put("温度 N 恢复正常", "4008");
        map.put("电流 A 恢复正常", "4009");
        map.put("电流 B 恢复正常", "4010");
        map.put("电流 C 恢复正常", "4011");
        return map.get(name);
    }

    /**
     * 回调地址：设备数据变化，订阅后推送设备数据变化通知
     *
     * @param
     * @return
     */
    public RespEntity deviceDataChanged(JSONObject jsonParam) throws Exception {
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType(jsonParam.getStr("deviceFlag"));
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        if (jsonParam.containsKey("notify_data")) {
            //世成电器
            return scdqElectric(jsonParam);
        }
        JSONObject service = jsonParam.getJSONObject("service");
        String serviceType = service.getStr("serviceType");//服务id
        if (serviceType.equals("IotStringReturn")) {
            //和远智能
            return jxHYZN(jsonParam);
        } else if (serviceType.equals("DataPackage")) {
            //盛善
            return jxSS(jsonParam);
        }
        return RespEntity.success();
    }

    public static void main(String[] args) {
        //String data = "RBk4NjM3MTYwNDAxNTk3MTQAAxEBBAAAAAAAHwAAAPoAAQAA//8AAD+AAAA/gAAACGgIugigAAACKAFx/+v/mgAAyF8=";
        //String hex = HexUtil.encodeHexStr(Base64Decoder.decode(data));
        //String first = hex.substring(72, 76);
        // firstTemperatureValue = Long.parseLong(first, 16);
        //System.out.println(String.valueOf(firstTemperatureValue.shortValue()).contains("-") + "------**" + firstTemperatureValue.shortValue());

//        Long firstTemperatureValue1 = Long.parseUnsignedLong(first, 16);
//        System.out.println(String.valueOf(firstTemperatureValue1));
        //QAJeA4QAAAMAAwADADIAANwA2wDcAAAAGABGAAAYAEYAABgARgAAFwBGAE8IY4ZgSAVQMg==
//        String data = HexUtil.encodeHexStr(Base64Decoder.decode("Mh04NjM3MTYwNDIyMzQ0ODEABVMAAAAAAAMAAAAAAB4AIAisAAAAAAAAAAAADQAOAAA="));
//        System.out.println(data);
//        String str = Integer.toBinaryString(Integer.parseInt("0007"));
//        System.out.println(str);
//        DecimalFormat df = new DecimalFormat("#.0");
//        String t = df.format((Long.parseLong("001e", 16)));
//        System.out.println(t);
        System.out.println(Long.parseLong("001d000d0034", 16));
        //Long.parseLong(data.substring(83, 99), 16)* 0.001;
        System.out.println(29 * 0.001);
    }

    //盛善
    public RespEntity jxSS(JSONObject jsonParam) throws Exception {
        logger.info("-------------------------盛善：" + jsonParam + "-------------------------------");
        JSONObject service = jsonParam.getJSONObject("service");
        JSONObject totalData = service.getJSONObject("data");//数据集
        String serviceId = service.getStr("serviceId");//服务id
        String time = contextLoads(service.getStr("eventTime"));//事件事件
        String data = totalData.getStr("Data");//需要的数据
        String hex = HexUtil.encodeHexStr(Base64Decoder.decode(data));
        //设备号
        String numberDecode = hex.substring(4, 36);
        String number = new String(HexUtil.decodeHex(numberDecode));
        number = number.substring(0, number.length() - 1);
        System.out.println(number);
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);
        //检测项数值
        Map<String, String> itemMap = getItme(jsonParamN);
        if (itemMap.isEmpty()) {
            return RespEntity.success();
        }
        if ("68".equals(totalData.getStr("Len"))) {
            SDF300(hex, number, itemMap, time);
        } else if ("50".equals(totalData.getStr("Len"))) {
            SDF400(hex, number, itemMap, time);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 盛善（电信）
     * @Date Created in 10:17 2023/2/9
     * @Param [jsonParam]
     */

    public RespEntity shengshanTelecom(JSONObject jsonParam) throws Exception {
        logger.info("-------------------------电信盛善：" + jsonParam + "-------------------------------");
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("shengshanElectricTelecom");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        JSONObject payload = jsonParam.getJSONObject("payload");
        //数据集
        JSONObject serviceData = payload.getJSONObject("serviceData");
        //时间
        String time = contextLoads(jsonParam.getLong("timestamp"));
        String data = serviceData.getStr("Data");//需要的数据
        String hex = HexUtil.encodeHexStr(Base64Decoder.decode(data));

        // crc校验
        // 获取数据携带的CRC
        String crc = serviceData.getStr("CRC");
        // 计算CRC
        byte[] bytes = hex2byte(hex);
        String crcCheck = getCRC(bytes);
        // 不反转计算CRC
        String value = String.valueOf(hexToInt(crcCheck));
        // 高低位反转
        crcCheck = crcCheck.substring(2) + crcCheck.substring(0, 2);
        String valueRev = String.valueOf(hexToInt(crcCheck));
        // 比较CRC是否一致
        if (!value.equals(crc) && !valueRev.equals(crc)) { // 不一致，返回
            return RespEntity.success();
        }

        //设备号
        String numberDecode = hex.substring(4, 36);
        String number = new String(HexUtil.decodeHex(numberDecode));
        number = number.substring(0, number.length() - 1);
        System.out.println(number);
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);
        if ("253".equals(serviceData.getStr("Header"))) {
            number = new String(HexUtil.decodeHex(hex.substring(0, 30)));
            String imsi = new String(HexUtil.decodeHex(hex.substring(32, 62)));
            jsonParamN.put("number", number);
            jsonParamN.put("iccid", imsi);
            this.asyncService.update_ICCID(jsonParamN);
            return RespEntity.success();
        }
        //检测项数值
        Map<String, String> itemMap = getItme(jsonParamN);
        if (itemMap.isEmpty()) {
            return RespEntity.success();
        }
        jsonParamN.put("deviceId",jsonParam.getStr("deviceId"));
        //异步更新电信AEP下发指令ID
        asyncService.updateDeviceTermId(jsonParamN);
        if ("68".equals(serviceData.getStr("Len"))) {
            SDF300(hex, number, itemMap, time);
        } else if ("50".equals(serviceData.getStr("Len"))) {
            SDF400(hex, number, itemMap, time);
        } else if ("48".equals(serviceData.getStr("Len"))) {
            SDF510(hex, number, itemMap, time);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 盛善（TCP）
     * @Date Created in 10:17 2023/2/9
     * @Param [jsonParam]
     */

    public RespEntity shengshanTCP(JSONObject jsonParam) throws Exception {
        logger.info("-------------------------电信盛善：" + jsonParam + "-------------------------------");
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("shengshanElectricTCP");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        //数据
        String hex = jsonParam.getStr("code");
        //时间
        String time = DateUtil.now();
        //设备号
        String numberDecode = hex.substring(10, 40);
        String number = new String(HexUtil.decodeHex(numberDecode));
        System.out.println(number);
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);
        //检测项数值
        Map<String, String> itemMap = getItme(jsonParamN);
        if (itemMap.isEmpty()) {
            return RespEntity.success();
        }
        hex = hex.substring(6, hex.length());
        if ("44".equals(hex.substring(0, 2))) {
            SDF300(hex, number, itemMap, time);
        } else if ("32".equals(hex.substring(0, 2))) {
            SDF400(hex, number, itemMap, time);
        }
        return RespEntity.success();
    }


    /**
     * @Author Xulumin
     * @Description 盛善SDF510（电信）
     * @Date Created in 2024.03.08
     * @Param [jsonParam]
     */
    public RespEntity SDF510(String hex, String number, Map<String, String> itemMap, String time) throws Exception {
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);
        // 格式化数据
        List<String> data = formatData(hex);
        // 设备类型
        String deviceType = "SDF510";
//        System.out.println(data);
        //报警位
        String alarmBit = String.valueOf(hexString2binaryString(data.get(21)));
        // 电量告警位
        String electricQuantityAlarmBit = Integer.toBinaryString(Integer.parseInt(data.get(26) + data.get(27)));
        if (electricQuantityAlarmBit.length() == 1) {
            electricQuantityAlarmBit = "0000" + electricQuantityAlarmBit;
        } else if (electricQuantityAlarmBit.length() == 2) {
            electricQuantityAlarmBit = "000" + electricQuantityAlarmBit;
        } else if (electricQuantityAlarmBit.length() == 3) {
            electricQuantityAlarmBit = "00" + electricQuantityAlarmBit;
        } else if (electricQuantityAlarmBit.length() == 4) {
            electricQuantityAlarmBit = "0" + electricQuantityAlarmBit;
        }
        //小数取值
        DecimalFormat df = new DecimalFormat("#.0");
        //漏电
        String ma = df.format((Long.parseLong(String.valueOf(hexToInt(data.get(28) + data.get(29))), 16)));
        System.out.println(ma);
        //温度1
        String t = df.format((Long.parseLong(data.get(30) + data.get(31), 16)));
        //温度2
        String t2 = df.format((Long.parseLong(data.get(32) + data.get(33), 16)));
        //电压
        String v = df.format((Long.parseLong(data.get(36) + data.get(37), 16) * 0.1));
        //电流
        String a = df.format((Long.parseLong(data.get(38) + data.get(39), 16) * 0.01));
        //功率
        String power = df.format((Long.parseLong(data.get(40) + data.get(41), 16) * 0.001));
        //功率因数
        String powerFactor = df.format((Long.parseLong(data.get(42) + data.get(43), 16) * 0.001));
        //电能
        String electricalEnergy = df.format((Long.parseLong(data.get(44) + data.get(45) + data.get(46) + data.get(47), 16) * 0.001));

        String alarmCode = "";
        String alarmValue = "";
        String alarmDes = "";
        //报警类型
        String AlarmTypeName = "";
        //报警标识位
        boolean flag = false;
        if (Double.parseDouble(ma) > Double.parseDouble(itemMap.get("漏电报警;max"))) {
            AlarmTypeName = "漏电报警";
            alarmCode = "2001";
            alarmDes = "漏电报警";
            alarmValue = ma;
            flag = true;
        } else if (Double.parseDouble(v) > Double.parseDouble(itemMap.get("电压报警;max"))) {
            AlarmTypeName = "过压报警";
            alarmCode = "2003";
            alarmDes = "A相过压报警";
            alarmValue = v;
            flag = true;
        } else if (Double.parseDouble(v) < Double.parseDouble(itemMap.get("电压报警;min"))) {
            AlarmTypeName = "欠压报警";
            alarmCode = "2002";
            alarmDes = "A相欠压报警";
            alarmValue = v;
            flag = true;
        } else if (Double.parseDouble(t) >= Double.parseDouble(itemMap.get("温度报警;max"))) {
            AlarmTypeName = "温度报警";
            alarmCode = "2008";
            alarmDes = "温度A报警";
            alarmValue = t;
            flag = true;
        } else if (electricQuantityAlarmBit.charAt(0) == '1') {
            AlarmTypeName = "过载报警";
            flag = true;

        } else if (Double.parseDouble(a) > Double.parseDouble(itemMap.get("电流报警;max"))) {
            AlarmTypeName = "过流报警";
            flag = true;
        } else if (electricQuantityAlarmBit.charAt(2) == '1') {
            AlarmTypeName = "缺相报警";
            flag = true;
        } else if (alarmBit.charAt(7) == '1') {
            AlarmTypeName = "漏电报警";
            flag = true;
        } else if (alarmBit.charAt(6) == '1') {
            AlarmTypeName = "温度T1报警";
            flag = true;
        } else if (alarmBit.charAt(5) == '1') {
            AlarmTypeName = "温度T2报警";
            flag = true;
        } else if (alarmBit.charAt(4) == '1') {
            AlarmTypeName = "短路/灭弧报警";
            flag = true;
        } else if (Double.parseDouble(power) > Double.parseDouble(itemMap.get("功率报警;max"))) {
            AlarmTypeName = "超过额定功率报警";
            flag = true;
        }
        //报警内容
        String content = "";
        if (AlarmTypeName.equals("漏电报警")) {
            content = AlarmTypeName + " 漏电值:" + ma;
        } else if (AlarmTypeName.equals("欠压报警")) {
            content = AlarmTypeName + " 电压:" + v;
        } else if (AlarmTypeName.equals("过压报警")) {
            content = AlarmTypeName + " 电压:" + v;
        } else if (AlarmTypeName.equals("缺相报警")) {
            content = AlarmTypeName;
        } else if (AlarmTypeName.equals("过流报警")) {
            content = AlarmTypeName + " 电流:" + a;
        } else if (AlarmTypeName.equals("过载报警")) {
            content = AlarmTypeName;
        } else if (AlarmTypeName.equals("温度T1报警")) {
            content = AlarmTypeName + " 温度:" + t;
        } else if (AlarmTypeName.equals("温度T2报警")) {
            content = AlarmTypeName + " 温度:" + t2;
        } else if (AlarmTypeName.equals("短路/灭弧报警")) {
            content = AlarmTypeName;
        } else if (AlarmTypeName.equals("超过额定功率报警")) {
            content = AlarmTypeName + " 功率:" + power;
        }
        boolean alarmFlag = false;
        if (flag) {//报警
            //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
            List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
            if (alarmList.isEmpty()) {//没有记录时添加
                AlarmRecord alarmRecord = new AlarmRecord();
                alarmRecord.setNumber(number);
                alarmRecord.setType(AlarmTypeName);
                alarmRecord.setTime(DateUtil.now());
                alarmRecordMapper.insert(alarmRecord);
                alarmFlag = true;
            } else {//有记录时判断加修改
                AlarmRecord alarmRecord = alarmList.get(0);
                String times = alarmRecord.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                boolean timeFlag = DateUtils.judgmentDate(times, 0.5);
                if (timeFlag) {
                    alarmRecord.setTime(DateUtil.now());
                    alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
                    alarmFlag = true;
                }
            }
            if (alarmFlag) {
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", content);
                jsonParamN.put("alarmTypeName", AlarmTypeName);
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 1);
                //return RespEntity.success(jsonParamN);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state", "2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        } else {
            jsonParamN.put("state", "1");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(getNormalItem("A相电压", v));
        jsonArray.add(getNormalItem("A相电流", a));
        jsonArray.add(getNormalItem("剩余电流", ma));
        jsonArray.add(getNormalItem("A线温度", t));
        jsonArray.add(getNormalItem("B线温度", t2));
        jsonArray.add(getNormalItem("总有功功率", power));
        jsonArray.add(getNormalItem("总功率因数", powerFactor));
        jsonArray.add(getNormalItem("有功电能", electricalEnergy));
        jsonParamN.put("paraminfo", jsonArray);
        jsonParamN.put("time", time);
        jsonParamN.put("NO", false);
        fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
        return RespEntity.success();

    }


    /**
     * @Author YangYu
     * @Description 盛善SDF300
     * @Date Created in 15:31 2022/7/29
     * @Param [data, number, itemMap, time]
     */

    public RespEntity SDF300(String hex, String number, Map<String, String> itemMap, String time) throws Exception {
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);
        //设备类型
        String deviceType = "SDF300"; //(36,38)
        //设备子类型
        String deviceSubType = "";
        String SubType = hex.substring(38, 40);
        if (SubType.equals("00")) {
            deviceSubType = "单相UI组合";
        }
        if (SubType.equals("01")) {
            deviceSubType = "单相多功能";
        }
        if (SubType.equals("10")) {
            deviceSubType = "三相UI组合";
        }
        if (SubType.equals("11")) {
            deviceSubType = "三相多功能";
        }
        //漏电通道
        String LeakageChannel = hex.substring(40, 42);
        //小数取值
        DecimalFormat df = new DecimalFormat("#.0");
        //温度路
        String Temperature = hex.substring(42, 44);
        String TemperaturePath = "";
        if (Temperature.equals("04")) {
            TemperaturePath = "4路温度";
        }
        if (Temperature.equals("03")) {
            TemperaturePath = "3路温度";
        }
        if (Temperature.equals("02")) {
            TemperaturePath = "2路温度";
        }
        if (Temperature.equals("01")) {
            TemperaturePath = "1路温度";
        }
        //剩余电流值
        String ResidualCurrent = hex.substring(60, 64);
        Long ResidualCurrentValue = Long.parseLong(ResidualCurrent, 16);
        //第一温度值
        String first = hex.substring(64, 68);
        Long firstTemperatureValue = Long.parseLong(first, 16);
        //第二温度值
        String second = hex.substring(68, 72);
        Long secondTemperatureValue = Long.parseLong(second, 16);
        //第三温度值
        String third = hex.substring(72, 76);
        Long thirdTemperatureValue = Long.parseLong(third, 16);
        //第四温度值
        String fourth = hex.substring(76, 80);
        Long fourthTemperatureValue = Long.parseLong(fourth, 16);
        //电压变比
        String PT = hex.substring(80, 88);
        Long ptl = Long.parseLong(PT, 16);
        Float pt = Float.intBitsToFloat(ptl.intValue());
        //电流变比
        String CT = hex.substring(88, 96);
        Long ctl = Long.parseLong(CT, 16);
        Float ct = Float.intBitsToFloat(ctl.intValue());
        //电压1
        String UA = hex.substring(96, 100);
        Long ua = Long.parseLong(UA, 16);
        String u1 = df.format((ua * 0.1 * pt));
        //电压2
        String UB = hex.substring(100, 104);
        Long ub = Long.parseLong(UB, 16);
        String u2 = df.format((ub * 0.1 * pt));
        //电压3
        String UC = hex.substring(104, 108);
        Long uc = Long.parseLong(UC, 16);
        String u3 = df.format((uc * 0.1 * pt));
        df = new DecimalFormat("#.000");
        //电流1
        String IA = hex.substring(108, 112);
        Long ia = Long.parseLong(IA, 16);
        String i1 = df.format((ia * 0.001 * ct));
        //电流2
        String IB = hex.substring(112, 116);
        Long ib = Long.parseLong(IB, 16);
        String i2 = df.format((ib * 0.001 * ct));
        //电流3
        String IC = hex.substring(116, 120);
        Long ic = Long.parseLong(IC, 16);
        String i3 = df.format((ic * 0.001 * ct));

        //功率
        String p = hex.substring(120, 124);
        String binaryP = HexToBin(p);
        String p1 = "";
        if (binaryP.charAt(0) == '0') {
            Long pl = Long.parseLong(p, 16);
            p1 = df.format((double) pl * 0.1 * (double) pt * (double) ct / 100.0);
        } else {
            int pl = negative(p);
            p1 = "-" + df.format((double) pl * 0.1 * (double) pt * (double) ct / 100.0);
        }
        //功率因数
        String PF = hex.substring(124, 128);
        String binaryPF = HexToBin(PF);
        String pf2 = "";
        if (binaryPF.charAt(0) == '0') {
            Long pf = Long.parseLong(PF, 16);
            pf2 = df.format((double) pf * 0.001);
        } else {
            int pf = negative(PF);
            pf2 = "-" + df.format((double) pf * 0.001);
        }
        //电能
        String EP = hex.substring(128, 136);
        Long ep = Long.parseLong(EP, 16);
        String ep3 = df.format((ep * 0.1 * pt * ct) / 100);
        //报警状态
        String AlarmStatu = hex.substring(44, 48);
        //报警类型
        String AlarmTypeName = "";
        //电量告警位
        String batteryWarning = hexString2binaryString(hex.substring(58, 60));
        String alramCode = "";
        String alramValue = "";
        String alramDes = "";
        //报警标识位
        boolean flag = false;
        if (Double.parseDouble(String.valueOf(ResidualCurrentValue)) > Double.parseDouble(itemMap.get("漏电报警;max"))) {
            AlarmTypeName = "漏电报警";
            alramCode = "2001";
            alramDes = "漏电报警";
            alramValue = ResidualCurrentValue.toString();
            flag = true;
        } else if (Double.parseDouble(u1) > Double.parseDouble(itemMap.get("电压报警;max"))) {
            AlarmTypeName = "过压报警";
            alramCode = "2003";
            alramDes = "A相过压报警";
            alramValue = u1;
            flag = true;
        } else if (Double.parseDouble(u1) < Double.parseDouble(itemMap.get("电压报警;min"))) {
            AlarmTypeName = "欠压报警";
            alramCode = "2002";
            alramDes = "A相欠压报警";
            alramValue = u1;
            flag = true;
        } else if (Double.parseDouble(u2) > Double.parseDouble(itemMap.get("电压报警;max"))) {
            AlarmTypeName = "过压报警";
            alramCode = "2004";
            alramDes = "B相过压报警";
            alramValue = u2;
            flag = true;
        } else if (Double.parseDouble(u2) < Double.parseDouble(itemMap.get("电压报警;min"))) {
            AlarmTypeName = "欠压报警";
            alramCode = "2005";
            alramDes = "B相欠压报警";
            alramValue = u2;
            flag = true;
        } else if (Double.parseDouble(u3) > Double.parseDouble(itemMap.get("电压报警;max"))) {
            AlarmTypeName = "过压报警";
            alramCode = "2007";
            alramDes = "C相过压报警";
            alramValue = u3;
            flag = true;
        } else if (Double.parseDouble(u3) < Double.parseDouble(itemMap.get("电压报警;min"))) {
            AlarmTypeName = "欠压报警";
            alramCode = "2006";
            alramDes = "C相欠压报警";
            alramValue = u3;
            flag = true;
        } else if (!String.valueOf(firstTemperatureValue.shortValue()).contains("-") && Double.parseDouble(String.valueOf(firstTemperatureValue.shortValue())) >= Double.parseDouble(itemMap.get("温度报警;max"))) {
            AlarmTypeName = "温度报警";
            alramCode = "2008";
            alramDes = "温度A报警";
            alramValue = String.valueOf(firstTemperatureValue.shortValue());
            flag = true;
        } else if (!String.valueOf(secondTemperatureValue.shortValue()).contains("-") && Double.parseDouble(String.valueOf(secondTemperatureValue.shortValue())) >= Double.parseDouble(itemMap.get("温度报警;max"))) {
            AlarmTypeName = "温度报警";
            alramCode = "2009";
            alramDes = "温度B报警";
            alramValue = String.valueOf(secondTemperatureValue.shortValue());
            flag = true;
        } else if (!String.valueOf(thirdTemperatureValue.shortValue()).contains("-") && Double.parseDouble(String.valueOf(thirdTemperatureValue.shortValue())) >= Double.parseDouble(itemMap.get("温度报警;max"))) {
            AlarmTypeName = "温度报警";
            alramCode = "2010";
            alramDes = "温度C报警";
            alramValue = String.valueOf(thirdTemperatureValue.shortValue());
            flag = true;
        } else if (!String.valueOf(fourthTemperatureValue.shortValue()).contains("-") && Double.parseDouble(String.valueOf(fourthTemperatureValue.shortValue())) >= Double.parseDouble(itemMap.get("温度报警;max"))) {
            AlarmTypeName = "温度报警";
            alramCode = "2011";
            alramDes = "温度N报警";
            alramValue = String.valueOf(fourthTemperatureValue.shortValue());
            flag = true;
        } else if (batteryWarning.substring(5, 6).equals("1")) {
            AlarmTypeName = "缺相报警";
            alramCode = "2012";
            alramDes = "电流A过载";
            alramValue = i1;
            flag = true;
        } else if (Double.parseDouble(i1) > Double.parseDouble(itemMap.get("电流报警;max")) || Double.parseDouble(i2) > Double.parseDouble(itemMap.get("电流报警;max")) || Double.parseDouble(i3) > Double.parseDouble(itemMap.get("电流报警;max"))) {
            AlarmTypeName = "过流报警";
            alramCode = "2012";
            alramDes = "电流A过载";
            alramValue = i1;
            flag = true;
        } else if (batteryWarning.substring(3, 4).equals("1")) {
            AlarmTypeName = "过载报警";
            alramCode = "2012";
            alramDes = "电流A过载";
            alramValue = i1;
            flag = true;
        } else if (Double.parseDouble(p1) > Double.parseDouble(itemMap.get("功率报警;max"))) {
            AlarmTypeName = "超过额定功率报警";
            flag = true;
        }
        String alarmStr = alramDes + ";;" + alramCode + ";;" + alramValue;
        //+"温度:["+"A线温度:"+firstTemperatureValue+"℃"+"B线温度:"+secondTemperatureValue+"℃"+"C线温度:"+thirdTemperatureValue+"℃"+"N线温度:"+fourthTemperatureValue+"℃";
        //报警内容
        String content = "";
        if (AlarmTypeName.equals("漏电报警")) {
            content = AlarmTypeName + " 漏电值:" + ResidualCurrentValue;
        } else if (AlarmTypeName.equals("欠压报警")) {
            content = AlarmTypeName + " 电压A:" + u1 + ";电压B:" + u2 + ";电压C:" + u3;
        } else if (AlarmTypeName.equals("过压报警")) {
            content = AlarmTypeName + " 电压A:" + u1 + ";电压B:" + u2 + ";电压C:" + u3;
        } else if (AlarmTypeName.equals("缺相报警")) {
            content = AlarmTypeName + " 电流1:" + i1 + ";电流2:" + i2 + ";电流3:" + i3;
        } else if (AlarmTypeName.equals("过流报警")) {
            content = AlarmTypeName + " 电流1:" + i1 + ";电流2:" + i2 + ";电流3:" + i3;
        } else if (AlarmTypeName.equals("过载报警")) {
            content = AlarmTypeName + " 功率:" + p1 + ";功率因数:" + pf2 + ";电能:" + ep3;
        } else if (AlarmTypeName.equals("温度报警")) {
            content = AlarmTypeName + " 温度1:" + firstTemperatureValue.shortValue() + ";温度2:" + secondTemperatureValue.shortValue() + ";温度3:" + thirdTemperatureValue.shortValue() + ";温度4:" + fourthTemperatureValue.shortValue();
        } else if (AlarmTypeName.equals("超过额定功率报警")) {
            content = AlarmTypeName + " 功率:" + p1;
        }
        boolean alarmFlag = false;
        if (flag) {//报警
            //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
            List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
            if (alarmList.isEmpty()) {//没有记录时添加
                AlarmRecord alarmRecord = new AlarmRecord();
                alarmRecord.setNumber(number);
                alarmRecord.setType(AlarmTypeName);
                alarmRecord.setTime(DateUtil.now());
                alarmRecordMapper.insert(alarmRecord);
                alarmFlag = true;
            } else {//有记录时判断加修改
                AlarmRecord alarmRecord = alarmList.get(0);
                String times = alarmRecord.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                boolean timeFlag = DateUtils.judgmentDate(times, 0.5);
                if (timeFlag) {
                    alarmRecord.setTime(DateUtil.now());
                    alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
                    alarmFlag = true;
                }
            }
            if (alarmFlag) {
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", content);
                jsonParamN.put("alarmTypeName", AlarmTypeName);
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 1);
                jsonParamN.put("alarmStr", alarmStr);
                //return RespEntity.success(jsonParamN);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state", "2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        } else {
            jsonParamN.put("state", "1");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(getNormalItem("A相电压", u1));
        jsonArray.add(getNormalItem("B相电压", u2));
        jsonArray.add(getNormalItem("C相电压", u3));
        jsonArray.add(getNormalItem("A相电流", i1));
        jsonArray.add(getNormalItem("B相电流", i2));
        jsonArray.add(getNormalItem("C相电流", i3));
        jsonArray.add(getNormalItem("剩余电流", ResidualCurrentValue));
        jsonArray.add(getNormalItem("A线温度", firstTemperatureValue.shortValue()));
        jsonArray.add(getNormalItem("B线温度", secondTemperatureValue.shortValue()));
        jsonArray.add(getNormalItem("C线温度", thirdTemperatureValue.shortValue()));
        jsonArray.add(getNormalItem("N线温度", fourthTemperatureValue.shortValue()));
        jsonArray.add(getNormalItem("总有功功率", p1));
        jsonArray.add(getNormalItem("总功率因数", pf2));
        jsonArray.add(getNormalItem("有功电能", ep3));
        //查询这个设备号上次平时数据的时间，如果时间间隔在0.25小时以内，不发送
//        List<NormalRecord> normalList = normalRecordMapper.selectList(new QueryWrapper<NormalRecord>().eq("number", number));
//        if (normalList.isEmpty()) {//没有记录时添加
//            NormalRecord normalRecord = new NormalRecord();
//            normalRecord.setNumber(number);
//            normalRecord.setTime(DateUtil.now());
//            normalRecordMapper.insert(normalRecord);
//        } else {//有记录时判断加修改
//            NormalRecord normalRecord = normalList.get(0);
//            String times = normalRecord.getTime();
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            boolean timeFlag = getDatePoor(new Date(), simpleDateFormat.parse(times), 0.25);
//            if (timeFlag) {
//                normalRecord.setTime(DateUtil.now());
//                normalRecordMapper.update(normalRecord, new QueryWrapper<NormalRecord>().eq("number", number));
//            }
//        }
        if (flag) {
            //查询这个设备号上次平时数据的时间，如果时间间隔在2分钟以内，不发送
            List<AlarmInNormalRecord> alarmNormalList = alarmInNormalRecordMapper.selectList(new QueryWrapper<AlarmInNormalRecord>().eq("number", number));
            if (alarmNormalList.isEmpty()) {//没有记录时添加
                AlarmInNormalRecord normalRecord = new AlarmInNormalRecord();
                normalRecord.setNumber(number);
                normalRecord.setTime(DateUtil.now());
                alarmInNormalRecordMapper.insert(normalRecord);
            } else {//有记录时判断加修改
                AlarmInNormalRecord normalRecord = alarmNormalList.get(0);
                String times = normalRecord.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                boolean timeFlag = DateUtils.judgmentDate(times, 0.04);
                if (timeFlag) {
                    normalRecord.setTime(DateUtil.now());
                    alarmInNormalRecordMapper.update(normalRecord, new QueryWrapper<AlarmInNormalRecord>().eq("number", number));
                    //大数据库
                    jsonParamN.put("dataType", "2");
                    fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                }
            }
        }
        jsonParamN.put("paraminfo", jsonArray);
        jsonParamN.put("time", time);
        fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
        //	String domain = "http://101.201.140.249:8000/electric-wf";
        //	String xml = HttpUtil.post(domain,jsonParam.toJSONString(1));
        return RespEntity.success(jsonParamN);
    }

    /**
     * @Author XuLumin
     * @Description 海康电设备641(电信)
     * @Date Created in 08:45 2024/1/25
     * @Param [jsonParam]
     */
    public RespEntity HK641(JSONObject jsonObject) {
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonObject.toString());
        alarmAllDeviceDataChanged.setType("hkElectricTelecom");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        try {
            if (!"dataReport".equals(jsonObject.getStr("messageType")) || "101".equals(jsonObject.getStr("serviceId"))) {
                return RespEntity.success();
            }
            DecimalFormat df = new DecimalFormat("0.00");
            String time = contextLoads(jsonObject.getLong("timestamp"));
            // 取数据
            JSONObject payload = jsonObject.getJSONObject("payload");
            // 判断通道数
            Integer chaNumbers = jsonObject.getJSONObject("payload").getInt("ch_nums");
            // 报警类型
            String AlarmTypeName = "";
            //报警标识位
            boolean flag = false;
            String alramCode = "";
            String alramValue = "";
            String alramDes = "";
            //设备类型
            String deviceType = "Hk641";
            //报警内容
            String content = "";
            JSONObject data = new JSONObject();
            data.put("number", jsonObject.getStr("IMEI"));
            String number = jsonObject.getStr("IMEI");

            JSONObject jsonParamN = new JSONObject();
            jsonParamN.put("number", number);
            //检测项数值
            Map<String, String> itemMap = getItme(jsonParamN);
            if (itemMap.isEmpty()) {
                return RespEntity.success();
            }

            String item[] = {"tem", "tem2", "tem3", "resCurrent", "u1", "u2", "u3", "i1", "i2", "i3", "ep", "actPower", "reaPower", "appPower", "powerFactor"};


            // 取数据
            for (int i = 1; i <= chaNumbers; i++) {
                String alerm = "ch_" + i + "_alarm_state";
                String fault = "ch_" + i + "_fault_state";
                String realValue = "ch_" + i + "_real_value";
                String faultValue = "ch_" + i + "_alarm_value";
                Double real_value = payload.getDouble(realValue);
                Double fault_value = payload.getDouble(faultValue);

                // 电压电流单位转换
                if ("u1".equals(item[i - 1]) || "u2".equals(item[i - 1]) || "u3".equals(item[i - 1])) {
                    real_value = Double.valueOf(real_value / 1000);
                    fault_value = Double.valueOf(fault_value / 1000);
                }
                if ("i1".equals(item[i - 1]) || "i2".equals(item[i - 1]) || "i3".equals(item[i - 1])) {
                    real_value = Double.valueOf(real_value / 1000);
                    fault_value = Double.valueOf(fault_value / 1000);
                }

                String alermState = payload.getStr(alerm);
                String faultState = payload.getStr(fault);
                // 判断状态,取值
                if ("0".equals(alermState)) {
                    data.put(item[i - 1], df.format(real_value));
                } else if ("6".equals(alermState)) {
                    data.put(item[i - 1], df.format(fault_value));
                    flag = true;
                    AlarmTypeName = "电弧报警";
                } else if ("2".equals(alermState)) {
                    data.put("ResidualCurrentValue", df.format(fault_value));
                    flag = true;
                    AlarmTypeName = "漏电报警";
                } else {
                    data.put(item[i - 1], df.format(fault_value));
                }

                // 判断故障
//                if (!"0".equals(faultState)) {
//                    if ("1".equals(faultState)) {
//                        flag = true;
//                        AlarmTypeName = i  + "通道,传感器短路故障";
//                    } else if ("2".equals(faultState)) {
//                        flag = true;
//                        AlarmTypeName = i + "通道,传感器断路故障";
//                    } else {
//                        flag = true;
//                        AlarmTypeName = i + "通道,传感器错解故障";
//                    }
//                }
            }

            // 判断报警
            if (!StringUtil.strIsNullOrEmpty(data.getStr("ResidualCurrentValue")) && (Double.parseDouble(data.getStr("u1")) > Double.parseDouble(itemMap.get("漏电报警;max")) || Double.parseDouble(data.getStr("u2")) > Double.parseDouble(itemMap.get("漏电报警;max")) || Double.parseDouble(data.getStr("u3")) > Double.parseDouble(itemMap.get("漏电报警;max")))) {
                AlarmTypeName = "漏电报警";
                alramCode = "2001";
                alramDes = "漏电报警";
                alramValue = data.getStr("ResidualCurrentValue").toString();
                flag = true;
            } else if (Double.parseDouble(data.getStr("u1")) > Double.parseDouble(itemMap.get("电压报警;max"))) {
                AlarmTypeName = "过压报警";
                alramCode = "2003";
                alramDes = "A相过压报警";
                alramValue = data.getStr("u1");
                flag = true;
            } else if (Double.parseDouble(data.getStr("u1")) < Double.parseDouble(itemMap.get("电压报警;min"))) {
                AlarmTypeName = "欠压报警";
                alramCode = "2002";
                alramDes = "A相欠压报警";
                alramValue = data.getStr("u1");
                flag = true;
            } else if (Double.parseDouble(data.getStr("u2")) > Double.parseDouble(itemMap.get("电压报警;max"))) {
                AlarmTypeName = "过压报警";
                alramCode = "2004";
                alramDes = "B相过压报警";
                alramValue = data.getStr("u2");
                flag = true;
            } else if (Double.parseDouble(data.getStr("u3")) < Double.parseDouble(itemMap.get("电压报警;min"))) {
                AlarmTypeName = "欠压报警";
                alramCode = "2005";
                alramDes = "B相欠压报警";
                alramValue = data.getStr("u3");
                flag = true;
            } else if (Double.parseDouble(data.getStr("u3")) > Double.parseDouble(itemMap.get("电压报警;max"))) {
                AlarmTypeName = "过压报警";
                alramCode = "2007";
                alramDes = "C相过压报警";
                alramValue = data.getStr("u3");
                flag = true;
            } else if (Double.parseDouble(data.getStr("u3")) < Double.parseDouble(itemMap.get("电压报警;min"))) {
                AlarmTypeName = "欠压报警";
                alramCode = "2006";
                alramDes = "C相欠压报警";
                alramValue = data.getStr("u3");
                flag = true;
            } else if (Double.parseDouble(data.getStr("tem")) >= Double.parseDouble(itemMap.get("温度报警;max"))) {
                AlarmTypeName = "温度报警";
                alramCode = "2008";
                alramDes = "温度报警";
                alramValue = data.getStr("tem");
                flag = true;
            } else if (Double.parseDouble(data.getStr("tem2")) >= Double.parseDouble(itemMap.get("温度报警;max"))) {
                AlarmTypeName = "温度报警";
                alramCode = "2009";
                alramDes = "温度B报警";
                alramValue = data.getStr("tem2");
                flag = true;
            } else if (Double.parseDouble(data.getStr("tem3")) >= Double.parseDouble(itemMap.get("温度报警;max"))) {
                AlarmTypeName = "温度报警";
                alramCode = "2010";
                alramDes = "温度C报警";
                alramValue = data.getStr("tem3");
                flag = true;
            } else if (Double.parseDouble(data.getStr("i1")) > Double.parseDouble(itemMap.get("电流报警;max")) || Double.parseDouble(data.getStr("i2")) > Double.parseDouble(itemMap.get("电流报警;max")) || Double.parseDouble(data.getStr("i3")) > Double.parseDouble(itemMap.get("电流报警;max"))) {
                AlarmTypeName = "过流报警";
                alramCode = "2012";
                alramDes = "电流A过载";
                alramValue = data.getStr("i1");
                flag = true;
            } else if (Double.parseDouble(data.getStr("actPower")) > Double.parseDouble(itemMap.get("功率报警;max"))) {
                AlarmTypeName = "超过额定功率报警";
                flag = true;
            }

            if (AlarmTypeName.equals("漏电报警")) {
                content = AlarmTypeName + " 漏电值:" + data.getStr("ResidualCurrentValue");
            } else if (AlarmTypeName.equals("欠压报警")) {
                content = AlarmTypeName + " 电压A:" + data.get("u1") + ";电压B:" + data.get("u2") + ";电压C:" + data.get("u3");
            } else if (AlarmTypeName.equals("过压报警")) {
                content = AlarmTypeName + " 电压A:" + data.get("u1") + ";电压B:" + data.get("u2") + ";电压C:" + data.get("u3");
            } else if (AlarmTypeName.equals("缺相报警")) {
                content = AlarmTypeName + " 电流1:" + data.get("i1") + ";电流2:" + data.get("i3") + ";电流3:" + data.get("i3");
            } else if (AlarmTypeName.equals("过流报警")) {
                content = AlarmTypeName + " 电流1:" + data.get("i1") + ";电流2:" + data.get("i3") + ";电流3:" + data.get("i3");
            } else if (AlarmTypeName.equals("过载报警")) {
                content = AlarmTypeName + " 功率:" + data.get("act_power") + ";功率因数:" + data.get("powerFactor");
            } else if (AlarmTypeName.equals("温度报警")) {
                content = AlarmTypeName + " 温度1:" + data.get("tem") + " 温度2:" + data.get("tem2") + " 温度3:" + data.get("tem3");
            } else if (AlarmTypeName.equals("超过额定功率报警")) {
                content = AlarmTypeName + " 功率:" + data.get("act_power");
            } else if (AlarmTypeName.equals("电弧报警")) {
                content = AlarmTypeName;
            }
            String alarmStr = alramDes + ";;" + alramCode + ";;" + alramValue;
            boolean alarmFlag = false;
            //设备号
            jsonParamN.put("number", jsonObject.get("IMEI"));
            if (flag) {//报警
                //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
                List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
                if (alarmList.isEmpty()) {//没有记录时添加
                    AlarmRecord alarmRecord = new AlarmRecord();
                    alarmRecord.setNumber(jsonObject.getStr("IMEI"));
                    alarmRecord.setType(AlarmTypeName);
                    alarmRecord.setTime(DateUtil.now());
                    alarmRecordMapper.insert(alarmRecord);
                    alarmFlag = true;
                } else {//有记录时判断加修改
                    AlarmRecord alarmRecord = alarmList.get(0);
                    String times = alarmRecord.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    boolean timeFlag = DateUtils.judgmentDate(times, 0.5);
                    if (timeFlag) {
                        alarmRecord.setTime(DateUtil.now());
                        alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", jsonObject.get("IMEI")).eq("type", AlarmTypeName));
                        alarmFlag = true;
                    }
                }
                if (alarmFlag) {
                    jsonParamN.put("interfaceType", "1");
                    jsonParamN.put("content", content);
                    jsonParamN.put("alarmTypeName", AlarmTypeName);
                    jsonParamN.put("alarmtime", time);
                    jsonParamN.put("deviceClassify", 1);
                    jsonParamN.put("alarmStr", alarmStr);
                    fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                    //异步更新设备状态
                    jsonParamN.put("state", "2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }
            } else {
                jsonParamN.put("state", "1");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }

            JSONArray jsonArray = new JSONArray();
            jsonArray.add(getNormalItem("A相电压", data.getStr("u1")));
            jsonArray.add(getNormalItem("B相电压", data.getStr("u2")));
            jsonArray.add(getNormalItem("C相电压", data.getStr("u3")));
            jsonArray.add(getNormalItem("A相电流", data.getStr("i1")));
            jsonArray.add(getNormalItem("B相电流", data.getStr("i2")));
            jsonArray.add(getNormalItem("C相电流", data.getStr("i3")));
            jsonArray.add(getNormalItem("剩余电流", data.getStr("resCurrent")));
            jsonArray.add(getNormalItem("A线温度", data.getStr("tem")));
            jsonArray.add(getNormalItem("B线温度", data.getStr("tem2")));
            jsonArray.add(getNormalItem("C线温度", data.getStr("tem3")));
            jsonArray.add(getNormalItem("总有功功率", data.getStr("actPower")));
            jsonArray.add(getNormalItem("总功率因数", data.getStr("powerFactor")));
            jsonArray.add(getNormalItem("有功电能", data.getStr("ep")));
            //正常数据
            jsonParamN.put("paraminfo", jsonArray);
            jsonParamN.put("time", time);
            fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
            //大数据库
            jsonParamN.put("dataType", "2");
            fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 盛善SDF400
     * @Date Created in 11:12 2022/7/29
     * @Param [data, number, itemMap]
     */

    public RespEntity SDF400(String data, String number, Map<String, String> itemMap, String time) throws Exception {
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);
        //报警位
        String alarmBit = Integer.toBinaryString(Integer.parseInt(data.substring(40, 44)));
        if (alarmBit.length() == 1) {
            alarmBit = "00" + alarmBit;
        } else if (alarmBit.length() == 2) {
            alarmBit = "0" + alarmBit;
        }
        //电量告警位
        String electricQuantityAlarmBit = Integer.toBinaryString(Integer.parseInt(data.substring(52, 56)));
        if (electricQuantityAlarmBit.length() == 1) {
            electricQuantityAlarmBit = "0000" + electricQuantityAlarmBit;
        } else if (electricQuantityAlarmBit.length() == 2) {
            electricQuantityAlarmBit = "000" + electricQuantityAlarmBit;
        } else if (electricQuantityAlarmBit.length() == 3) {
            electricQuantityAlarmBit = "00" + electricQuantityAlarmBit;
        } else if (electricQuantityAlarmBit.length() == 4) {
            electricQuantityAlarmBit = "0" + electricQuantityAlarmBit;
        }
        //小数取值
        DecimalFormat df = new DecimalFormat("#.0");
        //漏电
        String ma = df.format((Long.parseLong(data.substring(56, 60), 16)));
        //温度
        String t = df.format((Long.parseLong(data.substring(60, 64), 16)));
        //电压
        String v = df.format((Long.parseLong(data.substring(68, 72), 16) * 0.1));
        //电流
        String a = df.format((Long.parseLong(data.substring(72, 76), 16) * 0.01));
        //功率
        String power = df.format((Long.parseLong(data.substring(76, 80), 16) * 0.001));
        //功率因数
        String powerFactor = df.format((Long.parseLong(data.substring(80, 84), 16) * 0.001));
        //电能
        String electricalEnergy = df.format((Long.parseLong(data.substring(84, 92), 16) * 0.001));
        System.out.println(data.substring(84, 92));
        String alarmCode = "";
        String alarmValue = "";
        String alarmDes = "";
        //报警类型
        String AlarmTypeName = "";
        //报警标识位
        boolean flag = false;
        if (Double.parseDouble(String.valueOf(ma)) > Double.parseDouble(itemMap.get("漏电报警;max"))) {
            AlarmTypeName = "漏电报警";
            alarmCode = "2001";
            alarmDes = "漏电报警";
            alarmValue = ma;
            flag = true;
        } else if (Double.parseDouble(v) > Double.parseDouble(itemMap.get("电压报警;max"))) {
            AlarmTypeName = "过压报警";
            alarmCode = "2003";
            alarmDes = "A相过压报警";
            alarmValue = v;
            flag = true;
        } else if (Double.parseDouble(v) < Double.parseDouble(itemMap.get("电压报警;min"))) {
            AlarmTypeName = "欠压报警";
            alarmCode = "2002";
            alarmDes = "A相欠压报警";
            alarmValue = v;
            flag = true;
        } else if (Double.parseDouble(t) >= Double.parseDouble(itemMap.get("温度报警;max"))) {
            AlarmTypeName = "温度报警";
            alarmCode = "2008";
            alarmDes = "温度A报警";
            alarmValue = t;
            flag = true;
        } else if (electricQuantityAlarmBit.charAt(0) == '1') {
            AlarmTypeName = "过载报警";
            flag = true;

        } else if (Double.parseDouble(a) > Double.parseDouble(itemMap.get("电流报警;max"))) {
            AlarmTypeName = "过流报警";
            flag = true;
        } else if (electricQuantityAlarmBit.charAt(2) == '1') {
            AlarmTypeName = "缺相报警";
            flag = true;
        } else if (alarmBit.charAt(0) == '1') {
            AlarmTypeName = "电弧报警";
            flag = true;
        } else if (Double.parseDouble(power) > Double.parseDouble(itemMap.get("功率报警;max"))) {
            AlarmTypeName = "超过额定功率报警";
            flag = true;
        }
        //报警内容
        String content = "";
        if (AlarmTypeName.equals("漏电报警")) {
            content = AlarmTypeName + " 漏电值:" + ma;
        } else if (AlarmTypeName.equals("欠压报警")) {
            content = AlarmTypeName + " 电压:" + v;
        } else if (AlarmTypeName.equals("过压报警")) {
            content = AlarmTypeName + " 电压:" + v;
        } else if (AlarmTypeName.equals("缺相报警")) {
            content = AlarmTypeName;
        } else if (AlarmTypeName.equals("过流报警")) {
            content = AlarmTypeName + " 电流:" + a;
        } else if (AlarmTypeName.equals("过载报警")) {
            content = AlarmTypeName;
        } else if (AlarmTypeName.equals("温度报警")) {
            content = AlarmTypeName + " 温度:" + t;
        } else if (AlarmTypeName.equals("电弧报警")) {
            content = AlarmTypeName;
        } else if (AlarmTypeName.equals("超过额定功率报警")) {
            content = AlarmTypeName + " 功率:" + power;
        }
        boolean alarmFlag = false;
        if (flag) {//报警
            //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
            List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
            if (alarmList.isEmpty()) {//没有记录时添加
                AlarmRecord alarmRecord = new AlarmRecord();
                alarmRecord.setNumber(number);
                alarmRecord.setType(AlarmTypeName);
                alarmRecord.setTime(DateUtil.now());
                alarmRecordMapper.insert(alarmRecord);
                alarmFlag = true;
            } else {//有记录时判断加修改
                AlarmRecord alarmRecord = alarmList.get(0);
                String times = alarmRecord.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                boolean timeFlag = DateUtils.judgmentDate(times, 0.5);
                if (timeFlag) {
                    alarmRecord.setTime(DateUtil.now());
                    alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
                    alarmFlag = true;
                }
            }
            if (alarmFlag) {
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", content);
                jsonParamN.put("alarmTypeName", AlarmTypeName);
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 1);
                //return RespEntity.success(jsonParamN);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state", "2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        } else {
            jsonParamN.put("state", "1");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(getNormalItem("A相电压", v));
        jsonArray.add(getNormalItem("A相电流", a));
        jsonArray.add(getNormalItem("剩余电流", ma));
        jsonArray.add(getNormalItem("A线温度", t));
        jsonArray.add(getNormalItem("总有功功率", power));
        jsonArray.add(getNormalItem("总功率因数", powerFactor));
        jsonArray.add(getNormalItem("有功电能", electricalEnergy));
        jsonParamN.put("paraminfo", jsonArray);
        jsonParamN.put("time", time);
        jsonParamN.put("NO", false);
        fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 十六进制字符串转二进制字符串
     * @Date Created in 10:25 2022/3/18
     * @Param [hexString]
     */

    public static String hexString2binaryString(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0)
            return null;
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++) {
            tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }

    public JSONObject getNormalItem(String name, Object value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("value", value);
        return jsonObject;
    }

    //和远智能
    public RespEntity jxHYZN(JSONObject jsonParam) throws Exception {
        logger.info("和远智能---------" + jsonParam);
        JSONObject service = jsonParam.getJSONObject("service");
        JSONObject data = service.getJSONObject("data");//数据
        String serviceId = service.getStr("serviceId");//服务id
        String time = contextLoads(service.getStr("eventTime"));//事件事件
        if (!data.containsKey("stringa")) return RespEntity.success();
        JSONObject stringa = data.getJSONObject("stringa");//具体数据信息
        String Topic = stringa.getStr("Topic");//设备号//报警标识
        String strs[] = Topic.split("/");
        String type = strs[2];//warn,代表报警;real,平时数据
        String number = strs[0];//设备号
        String sValue = "";
        String rValue = "";
        String interfaceType = "";//接口类型：1 设备报警 2 消除报警
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);//imei号，即应用平台的设备号
        //查询符号类型匹配字典
        List<ElectricfireType> alarmTypeList = electricfireAlarmDeviceDataChangedMapper.getTypeList(number);
        Map<String, Object> alarmTypeMap = new HashMap<>();
        for (ElectricfireType ele : alarmTypeList) {
            alarmTypeMap.put(ele.getMark(), ele.getName());
        }
        if (type.equals("warn")) {//为报警
            interfaceType = "1";//接口类型：1 设备报警 2 消除报警
            String content = "";//报警内容
            String alarmTypeName = "";//报警大类名称：对应平台为小类名称
            Set<String> set = stringa.keySet();//报警信息的key
            JSONArray jSONArray = new JSONArray();
            for (String key : set) {
                if (key.equals("time") || key.equals("Topic")) continue;//不是报警信息跳过
                JSONObject bigValue = stringa.getJSONObject(key);
                Set<String> smallSet = bigValue.keySet();
                for (String small : smallSet) {
                    String smallValue = bigValue.getStr(small);
                    if (small.equals("s")) {//2:报警发生；3:报警恢复。
                        sValue = bigValue.getStr(small);
                        if (bigValue.getStr(small).equals("2")) {
                            smallValue = "报警发生";
                        } else if (bigValue.getStr(small).equals("3")) {
                            interfaceType = "2";
                            smallValue = "报警恢复";
                        }
                    }
                    if (small.equals("r")) {//数值
                        rValue = bigValue.getStr(small);
                    }
                    if (alarmTypeMap.get(small) != null && !small.equals("s") && !small.equals("h")) {
                        content = content + alarmTypeMap.get(small).toString() + ":" + smallValue + ";";//小类信息，这个还需要翻译一下small
                    }
                }
                if (alarmTypeMap.get(key) != null) {
                    alarmTypeName = alarmTypeName + alarmTypeMap.get(key) + ",";//报警大类信息，中间逗号分隔，需要翻译一下
                }
                JSONObject jSONObject = new JSONObject();
                if (alarmTypeMap.get(key) != null) {
                    jSONObject.put("name", alarmTypeMap.get(key).toString().replace(" ", ""));
                    jSONObject.put("value", rValue);
                    jSONArray.add(jSONObject);
                }

            }
            boolean alarmFlag = false;
            if (StrUtil.isNotBlank(alarmTypeName)) {
                alarmTypeName = alarmTypeName.substring(0, alarmTypeName.length() - 1);
                //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
                List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", alarmTypeName));
                if (alarmList.isEmpty()) {//没有记录时添加
                    AlarmRecord alarmRecord = new AlarmRecord();
                    alarmRecord.setNumber(number);
                    alarmRecord.setTime(DateUtil.now());
                    alarmRecord.setType(alarmTypeName);
                    alarmRecordMapper.insert(alarmRecord);
                    alarmFlag = true;
                } else {//有记录时判断加修改
                    AlarmRecord alarmRecord = alarmList.get(0);
                    String times = alarmRecord.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    boolean timeFlag = DateUtils.judgmentDate(times, 6);
                    ;
                    if (timeFlag) {
                        alarmRecord.setTime(DateUtil.now());
                        alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", alarmTypeName));
                        alarmFlag = true;
                    }
                }
            }
            if (alarmFlag) {
                if (StrUtil.isNotBlank(content)) {
                    content = content.substring(0, content.length() - 1);
                    content = alarmTypeName + " " + content;
                }
                //存储在数据库
                ElectricfireAlarmDeviceDataChanged electricfireAlarmDeviceDataChanged = new ElectricfireAlarmDeviceDataChanged();
                electricfireAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
                electricfireAlarmDeviceDataChanged.setJsondata(jsonParam.toString());
                electricfireAlarmDeviceDataChangedMapper.insert(electricfireAlarmDeviceDataChanged);
                //rest调用通知模块接口：
                jsonParamN.put("interfaceType", interfaceType);
                jsonParamN.put("content", content);
                jsonParamN.put("alarmTypeName", getAlarmMap(alarmTypeName));
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 1);
                if (stringa != null) jsonParamN.put("alarmStr", getFireAlarmStr(stringa, sValue, rValue));
                if (isAlarm(stringa, sValue, rValue, jsonParamN)) {
                    logger.info("-------------------------报警值为：" + rValue + "-------------------------------");
                    logger.info("-------------------------报警数据：" + jsonParam + "-------------------------------");
                    fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                    //异步更新设备状态
                    jsonParamN.put("state", "2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }
            }
            if (StrUtil.isNotBlank(alarmTypeName)) {
                //查询这个设备号上次平时数据的时间，如果时间间隔在2分钟以内，不发送
                List<AlarmInNormalRecord> alarmNormalList = alarmInNormalRecordMapper.selectList(new QueryWrapper<AlarmInNormalRecord>().eq("number", number));
                if (alarmNormalList.isEmpty()) {//没有记录时添加
                    AlarmInNormalRecord normalRecord = new AlarmInNormalRecord();
                    normalRecord.setNumber(number);
                    normalRecord.setTime(DateUtil.now());
                    alarmInNormalRecordMapper.insert(normalRecord);
                } else {//有记录时判断加修改
                    AlarmInNormalRecord normalRecord = alarmNormalList.get(0);
                    String times = normalRecord.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    boolean timeFlag = DateUtils.judgmentDate(times, 0.04);
                    ;
                    if (timeFlag) {
                        normalRecord.setTime(DateUtil.now());
                        alarmInNormalRecordMapper.update(normalRecord, new QueryWrapper<AlarmInNormalRecord>().eq("number", number));
                    }
                }
                jsonParamN.put("time", time);
                jsonParamN.put("paraminfo", jSONArray);
                fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
                //异步更新设备状态
                jsonParamN.put("state", "1");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        } else if (type.equals("real")) {//为平时数据
            JSONArray jSONArray = new JSONArray();
            Set<String> set = stringa.keySet();//报警信息的key
            for (String key : set) {
                if (key.equals("time") || Topic.equals("Topic")) continue;//不是报警信息跳过
                JSONObject jSONObject = new JSONObject();
                if (alarmTypeMap.get(key) != null) {
                    jSONObject.put("name", alarmTypeMap.get(key).toString().replace(" ", ""));
                    jSONObject.put("value", stringa.getStr(key));
                    jSONArray.add(jSONObject);
                }
            }
            //查询这个设备号上次平时数据的时间，如果时间间隔在0.25小时以内，不发送
//            List<NormalRecord> normalList = normalRecordMapper.selectList(new QueryWrapper<NormalRecord>().eq("number", number));
//            if (normalList.isEmpty()) {//没有记录时添加
//                NormalRecord normalRecord = new NormalRecord();
//                normalRecord.setNumber(number);
//                normalRecord.setTime(DateUtil.now());
//                normalRecordMapper.insert(normalRecord);
//            } else {//有记录时判断加修改
//                NormalRecord normalRecord = normalList.get(0);
//                String times = normalRecord.getTime();
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                boolean timeFlag = getDatePoor(new Date(), simpleDateFormat.parse(times), 0.25);
//                if (timeFlag) {
//                    normalRecord.setTime(DateUtil.now());
//                    normalRecordMapper.update(normalRecord, new QueryWrapper<NormalRecord>().eq("number", number));
//                    //大数据库
//                    jsonParamN.put("dataType", "2");
//                    fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
//                } else {
//                    return RespEntity.success();
//                }
//            }
            //大数据库
            jsonParamN.put("dataType", "2");
            fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
            //存储在数据库
            ElectricfireNormalDeviceDataChanged electricfireNormalDeviceDataChanged = new ElectricfireNormalDeviceDataChanged();
            electricfireNormalDeviceDataChanged.setId(UUID.randomUUID().toString());
            electricfireNormalDeviceDataChanged.setJsondata(jsonParam.toString());
            electricfireNormalDeviceDataChangedMapper.insert(electricfireNormalDeviceDataChanged);
            //rest调用平时数据添加接口：
            jsonParamN.put("paraminfo", jSONArray);
            jsonParamN.put("time", time);
            fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
            //异步更新设备状态
            jsonParamN.put("state", "1");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        //解析数据结束-------------------------------------------------------------------------------------------------------
        return RespEntity.success();
    }

    public String getAlarmMap(String str) {
        Map<String, String> map = new HashMap();
        map.put("A相电压", "过压报警");
        map.put("B相电压", "过压报警");
        map.put("C相电压", "过压报警");

        map.put("A相电流", "过流报警");
        map.put("B相电流", "过流报警");
        map.put("C相电流", "过流报警");

        map.put("A线温度", "温度报警");
        map.put("B线温度", "温度报警");
        map.put("C线温度", "温度报警");
        map.put("N线温度", "温度报警");

        map.put("剩余电流", "漏电报警");
        if (map.containsKey(str)) {
            return map.get(str);
        } else {
            return map.get("A相电压");
        }
    }


    /**
     * @Author YangYu
     * @Description 世成电器
     * @Date Created in 10:33 2020/11/30
     * @Param [jsonParam]
     */
    public RespEntity scdqElectric(JSONObject jsonParam) throws Exception {

        JSONObject notify_data = jsonParam.getJSONObject("notify_data");
        JSONArray services = notify_data.getJSONArray("services");
        JSONObject bigdata = (JSONObject) services.get(0);
        JSONObject data = bigdata.getJSONObject("data");
        //漏电实时数据
        String data_mA = data.getStr("data_mA");
        //漏电报警信息
        String fault_char_mA = data.getStr("fault_char_mA");
        //实时数据-A相电流
        String data_currentA = data.getStr("data_currentA");
        //实时数据-B相电流
        String data_currentB = data.getStr("data_currentB");
        //实时数据-C相电流
        String data_currentC = data.getStr("data_currentC");
        //三相电流报警信息
        String fault_char_current = data.getStr("data_mA");
        //实时数据-A相电压
        String data_voltageA = data.getStr("data_voltageA");
        //实时数据-B相电压
        String data_voltageB = data.getStr("data_voltageB");
        //实时数据-C相电压
        String data_voltageC = data.getStr("data_voltageC");
        //三相电压故障报警信息
        String fault_int_Voltage = data.getStr("fault_int_Voltage");
        //实时数据-温度1
        String data_T1 = data.getStr("data_T1");
        //温度故障报警信息1
        String fault_char_T1 = data.getStr("fault_char_T1");
        //实时数据-温度2
        String data_T2 = data.getStr("data_T2");
        //温度故障报警信息2
        String fault_char_T2 = data.getStr("fault_char_T2");
        //实时数据-温度3
        String data_T3 = data.getStr("data_T3");
        //温度故障报警信息3
        String fault_char_T3 = data.getStr("fault_char_T3");
        //实时数据-温度4
        String data_T4 = data.getStr("data_T4");
        //温度故障报警信息4
        String fault_char_T4 = data.getStr("fault_char_T4");
        //设备号
        String hex = HexUtil.encodeHexStr(Base64Decoder.decode(data.getStr("data_IMEI")));
        String number = hex.substring(1);
        //---------------------报警----------------------------------------------------------------
        //消防支队
        String alramCode = "";
        //消防支队
        String alramValue = "";
        //消防支队
        String alramDes = "";
        //报警类型
        String AlarmTypeName = "";
        //报警标识为
        boolean flag = false;
        if (fault_char_mA.equals("1")) {
            AlarmTypeName = "漏电报警";
            alramCode = "2001";
            alramDes = "漏电报警";
            alramValue = data_mA;
            flag = true;
        }
        if (fault_char_current.equals("1")) {
            AlarmTypeName = "过流报警";
            alramCode = "2012";
            alramDes = "电流A过载";
            alramValue = data_currentA;
            flag = true;
        }
        if (fault_char_current.equals("4")) {
            AlarmTypeName = "过流报警";
            alramCode = "2013";
            alramDes = "电流B过载";
            alramValue = data_currentB;
            flag = true;
        }
        if (fault_char_current.equals("16")) {
            AlarmTypeName = "过流报警";
            alramCode = "2014";
            alramDes = "电流C过载";
            alramValue = data_currentC;
            flag = true;
        }
        if (fault_int_Voltage.equals("256")) {
            AlarmTypeName = "过压报警";
            alramCode = "2003";
            alramDes = "A相过压报警";
            alramValue = data_voltageA;
            flag = true;
        }
        if (fault_int_Voltage.equals("4096")) {
            AlarmTypeName = "过压报警";
            alramCode = "2004";
            alramDes = "B相过压报警";
            alramValue = data_voltageB;
            flag = true;
        }
        if (fault_int_Voltage.equals("1")) {
            AlarmTypeName = "过压报警";
            alramCode = "2007";
            alramDes = "C相过压报警";
            alramValue = data_voltageC;
            flag = true;
        }
        if (fault_int_Voltage.equals("512")) {
            AlarmTypeName = "欠压报警";
            alramCode = "2002";
            alramDes = "A相欠压报警";
            alramValue = data_voltageA;
            flag = true;
        }
        if (fault_int_Voltage.equals("8192")) {
            AlarmTypeName = "欠压报警";
            alramCode = "2005";
            alramDes = "B相欠压报警";
            alramValue = data_voltageB;
            flag = true;
        }
        if (fault_int_Voltage.equals("2")) {
            AlarmTypeName = "欠压报警";
            alramCode = "2006";
            alramDes = "C相欠压报警";
            alramValue = data_voltageC;
            flag = true;
        }
        if (fault_char_T1.equals("1")) {
            AlarmTypeName = "温度报警";
            alramCode = "2008";
            alramDes = "温度A报警";
            alramValue = data_T1;
            flag = true;
        }
        if (fault_char_T2.equals("1")) {
            AlarmTypeName = "温度报警";
            alramCode = "2009";
            alramDes = "温度B报警";
            alramValue = data_T2;
            flag = true;
        }
        if (fault_char_T3.equals("1")) {
            AlarmTypeName = "温度报警";
            alramCode = "2010";
            alramDes = "温度C报警";
            alramValue = data_T3;
            flag = true;
        }
        if (fault_char_T4.equals("1")) {
            AlarmTypeName = "温度报警";
            alramCode = "2010";
            alramDes = "温度N报警";
            alramValue = data_T4;
            flag = true;
        }
        JSONObject jsonParamN = new JSONObject();
        //设备号
        jsonParamN.put("number", number);
        //消防支队
        String alarmStr = alramDes + ";;" + alramCode + ";;" + alramValue;
        //+"温度:["+"A线温度:"+firstTemperatureValue+"℃"+"B线温度:"+secondTemperatureValue+"℃"+"C线温度:"+thirdTemperatureValue+"℃"+"N线温度:"+fourthTemperatureValue+"℃";
        //报警内容
        String content = "";
        if (AlarmTypeName.equals("漏电报警")) {
            content = AlarmTypeName + " 漏电值:" + data_mA;
        } else if (AlarmTypeName.equals("欠压报警")) {
            content = AlarmTypeName + " 电压A:" + data_voltageA + ";电压B:" + data_voltageB + ";电压C:" + data_voltageC;
        } else if (AlarmTypeName.equals("过压报警")) {
            content = AlarmTypeName + " 电压A:" + data_voltageA + ";电压B:" + data_voltageB + ";电压C:" + data_voltageC;
        } else if (AlarmTypeName.equals("过流报警")) {
            content = AlarmTypeName + " 电流1:" + data_currentA + ";电流2:" + data_currentB + ";电流3:" + data_currentC;
        } else if (AlarmTypeName.equals("温度报警")) {
            content = AlarmTypeName + " 温度1:" + data_T1 + ";温度2:" + data_T2 + ";温度3:" + data_T3 + ";温度4:" + data_T4;
        }
        if (flag) {
            boolean alarmFlag = false;
            //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
            List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
            if (alarmList.isEmpty()) {//没有记录时添加
                AlarmRecord alarmRecord = new AlarmRecord();
                alarmRecord.setNumber(number);
                alarmRecord.setTime(DateUtil.now());
                alarmRecord.setType(AlarmTypeName);
                alarmRecordMapper.insert(alarmRecord);
                alarmFlag = true;
            } else {//有记录时判断加修改
                AlarmRecord alarmRecord = alarmList.get(0);
                String times = alarmRecord.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                boolean timeFlag = DateUtils.judgmentDate(times, 24);
                ;
                if (timeFlag) {
                    alarmRecord.setTime(DateUtil.now());
                    alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number));
                    alarmFlag = true;
                }
            }
            if (alarmFlag) {
                //存储在数据库
                ElectricfireOtherDeviceDataChanged electricfireOtherDeviceDataChanged = new ElectricfireOtherDeviceDataChanged();
                electricfireOtherDeviceDataChanged.setId(UUID.randomUUID().toString());
                electricfireOtherDeviceDataChanged.setJsondata(jsonParam.toString());
                electricfireOtherDeviceDataChangedMapper.insert(electricfireOtherDeviceDataChanged);
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", content);
                jsonParamN.put("alarmTypeName", AlarmTypeName);
                jsonParamN.put("alarmtime", DateUtil.now());
                jsonParamN.put("deviceClassify", 1);
                jsonParamN.put("alarmStr", alarmStr);
                //return RespEntity.success(jsonParamN);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state", "2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        }
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(getNormalItem("A相电压", data_voltageA));
        jsonArray.add(getNormalItem("B相电压", data_voltageB));
        jsonArray.add(getNormalItem("C相电压", data_voltageC));
        jsonArray.add(getNormalItem("A相电流", data_currentA));
        jsonArray.add(getNormalItem("B相电流", data_currentB));
        jsonArray.add(getNormalItem("C相电流", data_currentC));
        jsonArray.add(getNormalItem("剩余电流", data_mA));
        jsonArray.add(getNormalItem("A线温度", data_T1));
        jsonArray.add(getNormalItem("B线温度", data_T2));
        jsonArray.add(getNormalItem("C线温度", data_T3));
        jsonArray.add(getNormalItem("N线温度", data_T4));
        //查询这个设备号上次平时数据的时间，如果时间间隔在0.25小时以内，不发送
//        List<NormalRecord> normalList = normalRecordMapper.selectList(new QueryWrapper<NormalRecord>().eq("number", number));
//        if (normalList.isEmpty()) {//没有记录时添加
//            NormalRecord normalRecord = new NormalRecord();
//            normalRecord.setNumber(number.toString());
//            normalRecord.setTime(DateUtil.now());
//            normalRecordMapper.insert(normalRecord);
//        } else {//有记录时判断加修改
//            NormalRecord normalRecord = normalList.get(0);
//            String times = normalRecord.getTime();
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            boolean timeFlag = getDatePoor(new Date(), simpleDateFormat.parse(times), 0.25);
//            if (timeFlag) {
//                normalRecord.setTime(DateUtil.now());
//                normalRecordMapper.update(normalRecord, new QueryWrapper<NormalRecord>().eq("number", number));
//            }
//        }
        if (flag) {
            //查询这个设备号上次平时数据的时间，如果时间间隔在2分钟以内，不发送
            List<AlarmInNormalRecord> alarmNormalList = alarmInNormalRecordMapper.selectList(new QueryWrapper<AlarmInNormalRecord>().eq("number", number));
            if (alarmNormalList.isEmpty()) {//没有记录时添加
                AlarmInNormalRecord normalRecord = new AlarmInNormalRecord();
                normalRecord.setNumber(number.toString());
                normalRecord.setTime(DateUtil.now());
                alarmInNormalRecordMapper.insert(normalRecord);
            } else {//有记录时判断加修改
                AlarmInNormalRecord normalRecord = alarmNormalList.get(0);
                String times = normalRecord.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                boolean timeFlag = DateUtils.judgmentDate(times, 0.04);
                ;
                if (timeFlag) {
                    normalRecord.setTime(DateUtil.now());
                    alarmInNormalRecordMapper.update(normalRecord, new QueryWrapper<AlarmInNormalRecord>().eq("number", number));
                    //大数据库
                    jsonParamN.put("dataType", "2");
                    fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                }
            }
        }
        //存储在数据库
        ElectricfireOtherNormalDeviceDataChanged electricfireOtherNormalDeviceDataChanged = new ElectricfireOtherNormalDeviceDataChanged();
        electricfireOtherNormalDeviceDataChanged.setId(UUID.randomUUID().toString());
        electricfireOtherNormalDeviceDataChanged.setJsondata(jsonParam.toString());
        electricfireOtherNormalDeviceDataChangedMapper.insert(electricfireOtherNormalDeviceDataChanged);
        jsonParamN.put("paraminfo", jsonArray);
        jsonParamN.put("time", DateUtil.now());
        fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
        //异步更新设备状态
        jsonParamN.put("state", "1");
        asyncService.updateDeviceCurrentState(jsonParamN);
        return RespEntity.success();
    }

    //将时间转化成北京时间
    public String contextLoads(String str) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date = sdf.parse(str);
        String strN = sdf2.format(date);
        return strN;
    }

    /**
     * @Author YangYu
     * @Description 世成电器（电信）
     * @Date Created in 13:55 2022/5/25
     * @Param [jsonParam]
     */

    public RespEntity scdqElectricTelecom(JSONObject jsonParam) throws Exception {
        //报警数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("scdqElectricTelecom");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        //设备号
        String number = jsonParam.getStr("IMEI");
        //报警时间
        String time = contextLoads(jsonParam.getLong("timestamp"));
        //数据
        String data = HexUtil.encodeHexStr(Base64Decoder.decode(jsonParam.getJSONObject("payload").getStr("APPdata")));
        //漏电实时数据
        Integer leakageRealtimeData = hexToInt(data.substring(2, 6));
        //A相电流
        Integer currentA = hexToInt(data.substring(12, 16));
        //B相电流
        Integer currentB = hexToInt(data.substring(16, 20));
        //C相电流
        Integer currentC = hexToInt(data.substring(20, 24));
        //A相电压
        Integer voltageA = hexToInt(data.substring(30, 34));
        //B相电压
        Integer voltageB = hexToInt(data.substring(34, 38));
        //C相电压
        Integer voltageC = hexToInt(data.substring(38, 42));
        //温度1
        Integer temperature1 = hexToInt(data.substring(46, 50));
        //温度2
        Integer temperature2 = hexToInt(data.substring(56, 60));
        //温度3
        Integer temperature3 = hexToInt(data.substring(66, 70));
        //温度4
        Integer temperature4 = hexToInt(data.substring(76, 80));
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);
        //检测项数值
        Map<String, String> itemMap = getItme(jsonParamN);
        if (itemMap.isEmpty()) {
            return RespEntity.success();
        }
        String alramCode = "";
        String alramValue = "";
        String alramDes = "";
        //报警类型
        String AlarmTypeName = "";
        //报警标识位
        boolean flag = false;
        if (voltageA != 0 || voltageB != 0 || voltageC != 0) {
            if (voltageA > Double.parseDouble(itemMap.get("电压报警;max"))) {
                AlarmTypeName = "过压报警";
                alramCode = "2003";
                alramDes = "A相过压报警";
                alramValue = voltageA.toString();
                flag = true;
            } else if (voltageA < Double.parseDouble(itemMap.get("电压报警;min"))) {
                AlarmTypeName = "欠压报警";
                alramCode = "2002";
                alramDes = "A相欠压报警";
                alramValue = voltageA.toString();
                flag = true;
            } else if (voltageB > Double.parseDouble(itemMap.get("电压报警;max"))) {
                AlarmTypeName = "过压报警";
                alramCode = "2004";
                alramDes = "B相过压报警";
                alramValue = voltageB.toString();
                flag = true;
            } else if (voltageB < Double.parseDouble(itemMap.get("电压报警;min"))) {
                AlarmTypeName = "欠压报警";
                alramCode = "2005";
                alramDes = "B相欠压报警";
                alramValue = voltageB.toString();
                flag = true;
            } else if (voltageC > Double.parseDouble(itemMap.get("电压报警;max"))) {
                AlarmTypeName = "过压报警";
                alramCode = "2007";
                alramDes = "C相过压报警";
                alramValue = voltageC.toString();
                flag = true;
            } else if (voltageC < Double.parseDouble(itemMap.get("电压报警;min"))) {
                AlarmTypeName = "欠压报警";
                alramCode = "2006";
                alramDes = "C相欠压报警";
                alramValue = voltageC.toString();
                flag = true;
            }
        }
        if (leakageRealtimeData > Double.parseDouble(itemMap.get("漏电报警;max"))) {
            AlarmTypeName = "漏电报警";
            alramCode = "2001";
            alramDes = "漏电报警";
            alramValue = leakageRealtimeData.toString();
            flag = true;
        } else if (temperature1 >= Double.parseDouble(itemMap.get("温度报警;max"))) {
            AlarmTypeName = "温度报警";
            alramCode = "2008";
            alramDes = "温度1报警";
            alramValue = temperature1.toString();
            flag = true;
        } else if (temperature2 >= Double.parseDouble(itemMap.get("温度报警;max"))) {
            AlarmTypeName = "温度报警";
            alramCode = "2009";
            alramDes = "温度2报警";
            alramValue = temperature2.toString();
            flag = true;
        } else if (temperature3 >= Double.parseDouble(itemMap.get("温度报警;max"))) {
            AlarmTypeName = "温度报警";
            alramCode = "2010";
            alramDes = "温度3报警";
            alramValue = temperature3.toString();
            flag = true;
        } else if (temperature4 >= Double.parseDouble(itemMap.get("温度报警;max"))) {
            AlarmTypeName = "温度报警";
            alramCode = "2011";
            alramDes = "温度4报警";
            alramValue = temperature4.toString();
            flag = true;
        } else if (!data.substring(28, 30).equals("00")) {
            AlarmTypeName = "过流报警";
            alramCode = "2013";
            alramDes = "电流B过载";
            alramValue = currentB.toString();
            flag = true;
        }
        //消防参数
        String alarmStr = alramDes + ";;" + alramCode + ";;" + alramValue;

        //报警内容
        String content = "";
        if (AlarmTypeName.equals("漏电报警")) {
            content = AlarmTypeName + " 漏电值:" + leakageRealtimeData;
        } else if (AlarmTypeName.equals("欠压报警")) {
            content = AlarmTypeName + " 电压A:" + voltageA + ";电压B:" + voltageB + ";电压C:" + voltageC;
        } else if (AlarmTypeName.equals("过压报警")) {
            content = AlarmTypeName + " 电压A:" + voltageA + ";电压B:" + voltageB + ";电压C:" + voltageC;
        } else if (AlarmTypeName.equals("温度报警")) {
            content = AlarmTypeName + " 温度1:" + temperature1 + ";温度2:" + temperature2 + ";温度3:" + temperature3 + ";温度4:" + temperature4;
        } else if (AlarmTypeName.equals("过流报警")) {
            content = AlarmTypeName + " 电流A:" + currentA + ";电流B:" + currentB + ";电流C:" + currentC;
        }
        boolean alarmFlag = false;
        if (flag) {//报警
            //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
            List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
            if (alarmList.isEmpty()) {//没有记录时添加
                AlarmRecord alarmRecord = new AlarmRecord();
                alarmRecord.setNumber(number);
                alarmRecord.setType(AlarmTypeName);
                alarmRecord.setTime(DateUtil.now());
                alarmRecordMapper.insert(alarmRecord);
                alarmFlag = true;
            } else {//有记录时判断加修改
                AlarmRecord alarmRecord = alarmList.get(0);
                String times = alarmRecord.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                boolean timeFlag = DateUtils.judgmentDate(times, 0.5);
                ;
                if (timeFlag) {
                    alarmRecord.setTime(DateUtil.now());
                    alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number));
                    alarmFlag = true;
                }
            }
            if (alarmFlag) {
                //存储在数据库
                ElectricfireOtherDeviceDataChanged electricfireOtherDeviceDataChanged = new ElectricfireOtherDeviceDataChanged();
                electricfireOtherDeviceDataChanged.setId(UUID.randomUUID().toString());
                electricfireOtherDeviceDataChanged.setJsondata(jsonParam.toString());
                electricfireOtherDeviceDataChangedMapper.insert(electricfireOtherDeviceDataChanged);
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", content);
                jsonParamN.put("alarmTypeName", AlarmTypeName);
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 1);
                jsonParamN.put("alarmStr", alarmStr);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state", "2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        } else {
            //异步更新设备状态
            jsonParamN.put("state", "1");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(getNormalItem("A相电压", voltageA));
        jsonArray.add(getNormalItem("B相电压", voltageB));
        jsonArray.add(getNormalItem("C相电压", voltageC));
        jsonArray.add(getNormalItem("A相电流", currentA));
        jsonArray.add(getNormalItem("B相电流", currentB));
        jsonArray.add(getNormalItem("C相电流", currentC));
        jsonArray.add(getNormalItem("A线温度", temperature1));
        jsonArray.add(getNormalItem("B线温度", temperature2));
        jsonArray.add(getNormalItem("C线温度", temperature3));
        jsonArray.add(getNormalItem("N线温度", temperature4));
        jsonArray.add(getNormalItem("剩余电流", leakageRealtimeData));
        //存储在数据库
        ElectricfireOtherNormalDeviceDataChanged electricfireOtherNormalDeviceDataChanged = new ElectricfireOtherNormalDeviceDataChanged();
        electricfireOtherNormalDeviceDataChanged.setId(UUID.randomUUID().toString());
        electricfireOtherNormalDeviceDataChanged.setJsondata(jsonParam.toString());
        electricfireOtherNormalDeviceDataChangedMapper.insert(electricfireOtherNormalDeviceDataChanged);
        jsonParamN.put("paraminfo", jsonArray);
        jsonParamN.put("time", time);
        //正常数据添加
        fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 互联通电设备630（TCP）
     * @Date Created in 13:55 2022/5/25
     * @Param [jsonParam]
     */

    public RespEntity hltElectric630(JSONObject jsonParam) throws Exception {
        try {
            //数据4040160002012d140a020118869098043834617000000000710002960103010001ff2d1aff0202010400001f0000000000000d000d000c000d0000005c430000c842b1f268432ce7684311386943000000000000000000000000000000000000000000000000000000000000000000000000000000007b144842eb51b83e0ad7233e000000000d0b0a020118912323
            String data = jsonParam.getStr("code");
            //设备号
            String number = data.substring(24, 39);
            //报警时间
            String time = DateUtil.now();
            //数据单元标识
            String dataType = data.substring(54, 56);
            // 150上传终端设备部件实时状态数据
            if (hexToInt(dataType) != 150) {
                return RespEntity.success();
            }
            //小数取值
            DecimalFormat df = new DecimalFormat("#.0");
            //漏电实时数据
            Integer leakageRealtimeData = hexToInt(data.substring(96, 100));
            //温度1
            Integer temperature1 = hexToInt(data.substring(102, 104) + data.substring(100, 102));
            //温度2
            Integer temperature2 = hexToInt(data.substring(106, 108) + data.substring(104, 106));
            //温度3
            Integer temperature3 = hexToInt(data.substring(110, 112) + data.substring(108, 110));
            //温度4
            Integer temperature4 = hexToInt(data.substring(114, 116) + data.substring(112, 114));
            //A相电压
            Integer voltageA = hexToInt(data.substring(138, 140) + data.substring(136, 138) + data.substring(134, 136) + data.substring(132, 134));
            float voltageAF = Float.intBitsToFloat(voltageA);
            String voltageAS = df.format(voltageAF);
            //B相电压
            Integer voltageB = hexToInt(data.substring(146, 148) + data.substring(144, 146) + data.substring(142, 144) + data.substring(140, 142));
            float voltageBF = Float.intBitsToFloat(voltageB);
            String voltageBS = df.format(voltageBF);
            //C相电压
            Integer voltageC = hexToInt(data.substring(154, 156) + data.substring(152, 154) + data.substring(150, 152) + data.substring(148, 150));
            float voltageCF = Float.intBitsToFloat(voltageC);
            String voltageCS = df.format(voltageCF);
            //A相电流
            Integer currentA = hexToInt(data.substring(162, 164) + data.substring(160, 162) + data.substring(158, 160) + data.substring(156, 158));
            float currentAF = Float.intBitsToFloat(currentA);
            String currentAS = df.format(currentAF);
            //B相电流
            Integer currentB = hexToInt(data.substring(170, 172) + data.substring(168, 170) + data.substring(166, 168) + data.substring(164, 166));
            float currentBF = Float.intBitsToFloat(currentB);
            String currentBS = df.format(currentBF);
            //C相电流
            Integer currentC = hexToInt(data.substring(178, 180) + data.substring(176, 178) + data.substring(174, 176) + data.substring(172, 174));
            float currentCF = Float.intBitsToFloat(currentC);
            String currentCS = df.format(currentCF);
            //总有工功率
            Integer power = hexToInt(data.substring(210, 212) + data.substring(208, 210) + data.substring(206, 208) + data.substring(204, 206));
            float powerF = Float.intBitsToFloat(power);
            String powerS = df.format(powerF);
            //功率因数
            Integer powerFactor = hexToInt(data.substring(234, 236) + data.substring(232, 234) + data.substring(230, 232) + data.substring(228, 230));
            float powerFactorF = Float.intBitsToFloat(powerFactor);
            String powerFactorS = df.format(powerFactorF);
            //有功电能
            Integer electricEnergy = hexToInt(data.substring(250, 252) + data.substring(248, 250) + data.substring(246, 248) + data.substring(244, 246));
            float electricEnergyF = Float.intBitsToFloat(electricEnergy);
            String electricEnergyS = df.format(electricEnergyF);

            JSONObject jsonParamN = new JSONObject();
            jsonParamN.put("number", number);
            //检测项数值
            Map<String, String> itemMap = getItme(jsonParamN);
            if (itemMap.isEmpty()) {
                return RespEntity.success();
            }
            //报警类型
            String AlarmTypeName = "";
            //报警标识位
            boolean flag = false;
            if (voltageA != 0 || voltageB != 0 || voltageC != 0) {
                if (voltageAF > Double.parseDouble(itemMap.get("电压报警;max"))) {
                    AlarmTypeName = "过压报警";
                    flag = true;
                } else if (voltageAF < Double.parseDouble(itemMap.get("电压报警;min"))) {
                    AlarmTypeName = "欠压报警";
                    flag = true;
                } else if (voltageBF > Double.parseDouble(itemMap.get("电压报警;max"))) {
                    AlarmTypeName = "过压报警";
                    flag = true;
                } else if (voltageBF < Double.parseDouble(itemMap.get("电压报警;min"))) {
                    AlarmTypeName = "欠压报警";
                    flag = true;
                } else if (voltageCF > Double.parseDouble(itemMap.get("电压报警;max"))) {
                    AlarmTypeName = "过压报警";
                    flag = true;
                } else if (voltageCF < Double.parseDouble(itemMap.get("电压报警;min"))) {
                    AlarmTypeName = "欠压报警";
                    flag = true;
                }
            }
            if (leakageRealtimeData > Double.parseDouble(itemMap.get("漏电报警;max"))) {
                AlarmTypeName = "漏电报警";
                flag = true;
            } else if (temperature1 >= Double.parseDouble(itemMap.get("温度报警;max"))) {
                AlarmTypeName = "温度报警";
                flag = true;
            } else if (temperature2 >= Double.parseDouble(itemMap.get("温度报警;max"))) {
                AlarmTypeName = "温度报警";
                flag = true;
            } else if (temperature3 >= Double.parseDouble(itemMap.get("温度报警;max"))) {
                AlarmTypeName = "温度报警";
                flag = true;
            } else if (temperature4 >= Double.parseDouble(itemMap.get("温度报警;max"))) {
                AlarmTypeName = "温度报警";
                flag = true;
            }
            //报警内容
            String content = "";
            if (AlarmTypeName.equals("漏电报警")) {
                content = AlarmTypeName + " 漏电值:" + leakageRealtimeData;
            } else if (AlarmTypeName.equals("欠压报警")) {
                content = AlarmTypeName + " 电压A:" + voltageAS + ";电压B:" + voltageBS + ";电压C:" + voltageCS;
            } else if (AlarmTypeName.equals("过压报警")) {
                content = AlarmTypeName + " 电压A:" + voltageAS + ";电压B:" + voltageBS + ";电压C:" + voltageCS;
            } else if (AlarmTypeName.equals("温度报警")) {
                content = AlarmTypeName + " 温度1:" + temperature1 + ";温度2:" + temperature2 + ";温度3:" + temperature3 + ";温度4:" + temperature4;
            } else if (AlarmTypeName.equals("过流报警")) {
                content = AlarmTypeName + " 电流A:" + currentAS + ";电流B:" + currentBS + ";电流C:" + currentCS;
            }
            boolean alarmFlag = false;
            if (flag) {//报警
                //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
                List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
                if (alarmList.isEmpty()) {//没有记录时添加
                    AlarmRecord alarmRecord = new AlarmRecord();
                    alarmRecord.setNumber(number);
                    alarmRecord.setType(AlarmTypeName);
                    alarmRecord.setTime(DateUtil.now());
                    alarmRecordMapper.insert(alarmRecord);
                    alarmFlag = true;
                } else {//有记录时判断加修改
                    AlarmRecord alarmRecord = alarmList.get(0);
                    String times = alarmRecord.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    boolean timeFlag = DateUtils.judgmentDate(times, 0.5);
                    if (timeFlag) {
                        alarmRecord.setTime(DateUtil.now());
                        alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number));
                        alarmFlag = true;
                    }
                }
                if (alarmFlag) {
                    //存储在数据库
                    ElectricfireOtherDeviceDataChanged electricfireOtherDeviceDataChanged = new ElectricfireOtherDeviceDataChanged();
                    electricfireOtherDeviceDataChanged.setId(UUID.randomUUID().toString());
                    electricfireOtherDeviceDataChanged.setJsondata(jsonParam.toString());
                    electricfireOtherDeviceDataChangedMapper.insert(electricfireOtherDeviceDataChanged);
                    jsonParamN.put("interfaceType", "1");
                    jsonParamN.put("content", content);
                    jsonParamN.put("alarmTypeName", AlarmTypeName);
                    jsonParamN.put("alarmtime", time);
                    jsonParamN.put("deviceClassify", 1);
                    fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                    //异步更新设备状态
                    jsonParamN.put("state", "2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }
            } else {
                //异步更新设备状态
                jsonParamN.put("state", "1");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(getNormalItem("A相电压", voltageAS));
            jsonArray.add(getNormalItem("B相电压", voltageBS));
            jsonArray.add(getNormalItem("C相电压", voltageCS));
            jsonArray.add(getNormalItem("A相电流", currentAS));
            jsonArray.add(getNormalItem("B相电流", currentBS));
            jsonArray.add(getNormalItem("C相电流", currentCS));
            jsonArray.add(getNormalItem("A线温度", temperature1));
            jsonArray.add(getNormalItem("B线温度", temperature2));
            jsonArray.add(getNormalItem("C线温度", temperature3));
            jsonArray.add(getNormalItem("N线温度", temperature4));
            jsonArray.add(getNormalItem("剩余电流", leakageRealtimeData));
            jsonArray.add(getNormalItem("总有功功率", powerS));
            jsonArray.add(getNormalItem("总功率因数", powerFactorS));
            jsonArray.add(getNormalItem("有功电能", electricEnergyS));
            jsonParamN.put("paraminfo", jsonArray);
            jsonParamN.put("time", time);
            //正常数据添加
            fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
        } catch (Exception e) {
            System.out.println(e);
        }
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 互联通电设备640（TCP）
     * @Date Created in 17:15 2024/1/16
     * @Param [jsonParam]
     */

    public RespEntity hltElectric640(JSONObject jsonParam) throws Exception {
        try {
            String code = jsonParam.getStr("code");
            JSONObject analyze = analyze(code);
            List<String> strings = analyzeData640(analyze.getStr("数据体"));
            //报警时间
            String time = DateUtil.now();
            //数据单元标识
            String dataType = getInfo(strings, -1, 1);
            // 150上传终端设备部件实时状态数据
            if (hexToInt(dataType) != 150) {
                return RespEntity.success();
            }
            // 设备编码
            String number = analyze.getStr("设备地址");
            // 使能状态
            String enableStatus = getInfo(strings, 14, 1);
            // 报警状态
            String warnStatus = getInfo(strings, 15, 1);
            // 漏电
            Integer leakageRealtimeData = hexToInt(getInfo(strings, 19, 2));
            // 温度
            Integer tem = hexToInt(getInfo(strings, 21, 2));
            // 电压
            String voltageV = getIeee754(getInfo(strings, 37, 4));
            // 电流
            String currentA = getIeee754(getInfo(strings, 41, 4));
            // 有功功率
            String activePowerKw = getIeee754(getInfo(strings, 45, 4));
            // 功率因数
            String powerFactorPf = getIeee754(getInfo(strings, 57, 4));
            // 有功电能
            String reactiveEnergyKvarh = getIeee754(getInfo(strings, 65, 4));
            JSONObject jsonParamN = new JSONObject();
            jsonParamN.put("number", number);
            //检测项数值
            Map<String, String> itemMap = getItme(jsonParamN);
            if (itemMap.isEmpty()) {
                return RespEntity.success();
            }
            //报警类型
            String AlarmTypeName = "";
            //报警标识位
            boolean flag = false;
            if (Double.parseDouble(voltageV) != 0) {
                if (Double.parseDouble(voltageV) > Double.parseDouble(itemMap.get("电压报警;max"))) {
                    AlarmTypeName = "过压报警";
                    flag = true;
                } else if (Double.parseDouble(voltageV) < Double.parseDouble(itemMap.get("电压报警;min"))) {
                    AlarmTypeName = "欠压报警";
                    flag = true;
                }
            }
            if (leakageRealtimeData > Double.parseDouble(itemMap.get("漏电报警;max"))) {
                AlarmTypeName = "漏电报警";
                flag = true;
            } else if (tem >= Double.parseDouble(itemMap.get("温度报警;max"))) {
                AlarmTypeName = "温度报警";
                flag = true;
            }
            //报警内容
            String content = "";
            if (AlarmTypeName.equals("漏电报警")) {
                content = AlarmTypeName + " 漏电值:" + leakageRealtimeData;
            } else if (AlarmTypeName.equals("欠压报警")) {
                content = AlarmTypeName + " 电压A:" + voltageV;
            } else if (AlarmTypeName.equals("过压报警")) {
                content = AlarmTypeName + " 电压A:" + voltageV;
            } else if (AlarmTypeName.equals("温度报警")) {
                content = AlarmTypeName + " 温度1:" + tem;
            } else if (AlarmTypeName.equals("过流报警")) {
                content = AlarmTypeName + " 电流A:" + currentA;
            }
            boolean alarmFlag = false;
            if (flag) {//报警
                //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
                List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
                if (alarmList.isEmpty()) {//没有记录时添加
                    AlarmRecord alarmRecord = new AlarmRecord();
                    alarmRecord.setNumber(number);
                    alarmRecord.setType(AlarmTypeName);
                    alarmRecord.setTime(DateUtil.now());
                    alarmRecordMapper.insert(alarmRecord);
                    alarmFlag = true;
                } else {//有记录时判断加修改
                    AlarmRecord alarmRecord = alarmList.get(0);
                    String times = alarmRecord.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    boolean timeFlag = DateUtils.judgmentDate(times, 0.5);
                    if (timeFlag) {
                        alarmRecord.setTime(DateUtil.now());
                        alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number));
                        alarmFlag = true;
                    }
                }
                if (alarmFlag) {
                    //存储在数据库
                    ElectricfireOtherDeviceDataChanged electricfireOtherDeviceDataChanged = new ElectricfireOtherDeviceDataChanged();
                    electricfireOtherDeviceDataChanged.setId(UUID.randomUUID().toString());
                    electricfireOtherDeviceDataChanged.setJsondata(jsonParam.toString());
                    electricfireOtherDeviceDataChangedMapper.insert(electricfireOtherDeviceDataChanged);
                    jsonParamN.put("interfaceType", "1");
                    jsonParamN.put("content", content);
                    jsonParamN.put("alarmTypeName", AlarmTypeName);
                    jsonParamN.put("alarmtime", time);
                    jsonParamN.put("deviceClassify", 1);
                    fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                    //异步更新设备状态
                    jsonParamN.put("state", "2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }
            } else {
                //异步更新设备状态
                jsonParamN.put("state", "1");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(getNormalItem("A相电压", voltageV));
            jsonArray.add(getNormalItem("A相电流", currentA));
            jsonArray.add(getNormalItem("A线温度", tem));
            jsonArray.add(getNormalItem("剩余电流", leakageRealtimeData));
            jsonArray.add(getNormalItem("总有功功率", activePowerKw));
            jsonArray.add(getNormalItem("总功率因数", powerFactorPf));
            jsonArray.add(getNormalItem("有功电能", reactiveEnergyKvarh));
            jsonParamN.put("paraminfo", jsonArray);
            jsonParamN.put("time", time);
            //正常数据添加
            fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 海康电设备（TCP641）
     * @Date Created in 上午11:02 2025/3/27
     * @Param [jsonParam]
     */

    public RespEntity electricHik(JSONObject jsonParam) throws ParseException {
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("electricHik");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        //数据
        String code = jsonParam.getStr("code");
        //命令字节
        Integer command = hexToInt(code.substring(52,54));

        //只解析用传发送数据
        if (command == 2){
            //类型标志
            Integer type = hexToInt(code.substring(54,56));
            //上传建筑消防设施部件运行状态
            if (type == 210){
                //设备编号
                String number = ByteUtil.hexToStr(code.substring(62,80));
                //温度1
                double temperature1 = HexUtils.hexToNegative(code.substring(98,106));
                //温度2
                double temperature2 = HexUtils.hexToNegative(code.substring(120,128));
                //温度3
                double temperature3 =  HexUtils.hexToNegative(code.substring(142,150));
                //剩余电流
                String residualCurrents = code.substring(164,172);
                double residualCurrent = HexUtils.hex16To10(residualCurrents.substring(6, 8) + residualCurrents.substring(4, 6) + residualCurrents.substring(2, 4) + residualCurrents.substring(0, 2));
                //电压A
                String voltageAs = code.substring(186,194);
                double voltageA = (double) HexUtils.hex16To10(voltageAs.substring(6, 8) + voltageAs.substring(4, 6) + voltageAs.substring(2, 4) + voltageAs.substring(0, 2)) / 10;
                //电压B
                String voltageBs = code.substring(208,216);
                double voltageB = (double) HexUtils.hex16To10(voltageBs.substring(6, 8) + voltageBs.substring(4, 6) + voltageBs.substring(2, 4) + voltageBs.substring(0, 2)) / 10;
                //电压C
                String voltageCs = code.substring(230,238);
                double voltageC = (double) HexUtils.hex16To10(voltageCs.substring(6, 8) + voltageCs.substring(4, 6) + voltageCs.substring(2, 4) + voltageCs.substring(0, 2)) / 10;
                //电流A
                String currentAs = code.substring(252,260);
                double currentA = (double) HexUtils.hex16To10(currentAs.substring(6, 8) + currentAs.substring(4, 6) + currentAs.substring(2, 4) + currentAs.substring(0, 2)) / 10;
                //电流B
                String currentBs = code.substring(274,282);
                double currentB = (double) HexUtils.hex16To10(currentBs.substring(6, 8) + currentBs.substring(4, 6) + currentBs.substring(2, 4) + currentBs.substring(0, 2)) / 10;
                //电流C
                String currentCs = code.substring(296,304);
                double currentC = (double) HexUtils.hex16To10(currentCs.substring(6, 8) + currentCs.substring(4, 6) + currentCs.substring(2, 4) + currentCs.substring(0, 2)) / 10;
                //电能
                String electricalEnergyS = code.substring(318,326);
                double electricalEnergy = (double) HexUtils.hex16To10(electricalEnergyS.substring(6, 8) + electricalEnergyS.substring(4, 6) + electricalEnergyS.substring(2, 4) + electricalEnergyS.substring(0, 2)) / 100;
                JSONObject jsonParamN = new JSONObject();
                //时间
                String time = DateUtil.now();
                jsonParamN.put("number", number);
                //检测项数值
                Map<String, String> itemMap = getItme(jsonParamN);
                if (itemMap.isEmpty()) {
                    return RespEntity.success();
                }
                //报警类型
                String AlarmTypeName = "";
                String alramCode = "";
                double alramValue = 0;
                String alramDes = "";
                //报警标识位
                boolean flag = false;
                if (voltageA > Double.parseDouble(itemMap.get("电压报警;max"))) {
                    AlarmTypeName = "过压报警";
                    alramCode = "2003";
                    alramDes = "A相过压报警";
                    alramValue = voltageA;
                    flag = true;
                } else if (voltageA < Double.parseDouble(itemMap.get("电压报警;min"))) {
                    AlarmTypeName = "欠压报警";
                    alramCode = "2002";
                    alramDes = "A相欠压报警";
                    alramValue = voltageA;
                    flag = true;
                } else if (voltageB > Double.parseDouble(itemMap.get("电压报警;max"))) {
                    AlarmTypeName = "过压报警";
                    alramCode = "2004";
                    alramDes = "B相过压报警";
                    alramValue = voltageB;
                    flag = true;
                } else if (voltageB < Double.parseDouble(itemMap.get("电压报警;min"))) {
                    AlarmTypeName = "欠压报警";
                    alramCode = "2005";
                    alramDes = "B相欠压报警";
                    alramValue = voltageB;
                    flag = true;
                } else if (voltageC > Double.parseDouble(itemMap.get("电压报警;max"))) {
                    AlarmTypeName = "过压报警";
                    alramCode = "2007";
                    alramDes = "C相过压报警";
                    alramValue = voltageC;
                    flag = true;
                } else if (voltageC < Double.parseDouble(itemMap.get("电压报警;min"))) {
                    AlarmTypeName = "欠压报警";
                    alramCode = "2006";
                    alramDes = "C相欠压报警";
                    alramValue = voltageC;
                    flag = true;
                } else if (temperature1>= Double.parseDouble(itemMap.get("温度报警;max"))) {
                    AlarmTypeName = "温度报警";
                    alramCode = "2008";
                    alramDes = "温度A报警";
                    alramValue = temperature1;
                    flag = true;
                } else if (temperature2 >= Double.parseDouble(itemMap.get("温度报警;max"))) {
                    AlarmTypeName = "温度报警";
                    alramCode = "2009";
                    alramDes = "温度B报警";
                    alramValue = temperature2;
                    flag = true;
                } else if (temperature3 >= Double.parseDouble(itemMap.get("温度报警;max"))) {
                    AlarmTypeName = "温度报警";
                    alramCode = "2010";
                    alramDes = "温度C报警";
                    alramValue = temperature3;
                    flag = true;
                }
                String alarmStr = alramDes + ";;" + alramCode + ";;" + alramValue;
                //报警内容
                String content = "";
                if (AlarmTypeName.equals("欠压报警")) {
                    content = AlarmTypeName + " 电压A:" + voltageA + ";电压B:" + voltageB + ";电压C:" + voltageC;
                } else if (AlarmTypeName.equals("过压报警")) {
                    content = AlarmTypeName + " 电压A:" + voltageA + ";电压B:" + voltageB + ";电压C:" + voltageC;
                } else if (AlarmTypeName.equals("温度报警")) {
                    content = AlarmTypeName + " 温度1:" + temperature1 + ";温度2:" + temperature2 + ";温度3:" + temperature3;
                }
                boolean alarmFlag = false;
                if (flag) {//报警
                    //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
                    List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", AlarmTypeName));
                    if (alarmList.isEmpty()) {//没有记录时添加
                        AlarmRecord alarmRecord = new AlarmRecord();
                        alarmRecord.setNumber(number);
                        alarmRecord.setTime(DateUtil.now());
                        alarmRecord.setType(AlarmTypeName);
                        alarmRecordMapper.insert(alarmRecord);
                        alarmFlag = true;
                    } else {//有记录时判断加修改
                        AlarmRecord alarmRecord = alarmList.get(0);
                        String times = alarmRecord.getTime();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        boolean timeFlag = getDatePoor(new Date(), simpleDateFormat.parse(times), 6);
                        if (timeFlag) {
                            alarmRecord.setTime(DateUtil.now());
                            alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number));
                            alarmFlag = true;
                        }
                    }
                    if (alarmFlag) {
                        jsonParamN.put("interfaceType", "1");
                        jsonParamN.put("content", content);
                        jsonParamN.put("alarmTypeName", AlarmTypeName);
                        jsonParamN.put("alarmtime", time);
                        jsonParamN.put("deviceClassify", 1);
                        jsonParamN.put("alarmStr", alarmStr);
                        //return RespEntity.success(jsonParamN);
                        fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                    }
                }
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(getNormalItem("A相电压", voltageA));
                jsonArray.add(getNormalItem("B相电压", voltageB));
                jsonArray.add(getNormalItem("C相电压", voltageC));
                jsonArray.add(getNormalItem("A相电流", currentA));
                jsonArray.add(getNormalItem("B相电流", currentB));
                jsonArray.add(getNormalItem("C相电流", currentC));
                jsonArray.add(getNormalItem("剩余电流", residualCurrent));
                jsonArray.add(getNormalItem("A线温度", temperature1));
                jsonArray.add(getNormalItem("B线温度", temperature2));
                jsonArray.add(getNormalItem("C线温度", temperature3));
                jsonArray.add(getNormalItem("N线温度", 0));
                jsonArray.add(getNormalItem("总有功功率", 0));
                jsonArray.add(getNormalItem("总功率因数", 0));
                jsonArray.add(getNormalItem("有功电能", electricalEnergy));
                //查询这个设备号上次平时数据的时间，如果时间间隔在0.25小时以内，不发送
                if (flag) {
                    //查询这个设备号上次平时数据的时间，如果时间间隔在2分钟以内，不发送
                    List<AlarmInNormalRecord> alarmNormalList = alarmInNormalRecordMapper.selectList(new QueryWrapper<AlarmInNormalRecord>().eq("number", number));
                    if (alarmNormalList.isEmpty()) {//没有记录时添加
                        AlarmInNormalRecord normalRecord = new AlarmInNormalRecord();
                        normalRecord.setNumber(number);
                        normalRecord.setTime(DateUtil.now());
                        alarmInNormalRecordMapper.insert(normalRecord);
                    } else {//有记录时判断加修改
                        AlarmInNormalRecord normalRecord = alarmNormalList.get(0);
                        String times = normalRecord.getTime();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        boolean timeFlag = getDatePoor(new Date(), simpleDateFormat.parse(times), 0.04);
                        if (timeFlag) {
                            normalRecord.setTime(DateUtil.now());
                            alarmInNormalRecordMapper.update(normalRecord, new QueryWrapper<AlarmInNormalRecord>().eq("number", number).eq("type", AlarmTypeName));
                            //大数据库
                            jsonParamN.put("dataType", "2");
                            fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                        }
                    }
                }
                jsonParamN.put("paraminfo", jsonArray);
                jsonParamN.put("time", time);
                fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
            }
        }
        return RespEntity.success();
    }

    /**
     * 取数据
     */
    public static String getInfo(List<String> data, Integer index, Integer lenght) {
        if (index >= data.size() + 3) {
            return "error";
        }
        StringBuffer stringBuffer = new StringBuffer();
        if (lenght == 1) {
            for (int i = index; i < lenght + index; i++) {
                stringBuffer.append(data.get(i + 1));
            }
            return stringBuffer.toString();
        } else if (lenght > 1) {
            int i;
            for (i = index + lenght - 1; i >= index; i--) {
                stringBuffer.append(getInfo(data, i, 1));
            }
            return stringBuffer.toString();
        } else {
            return "error";
        }
    }

    /**
     * 格式化数据体
     */
    public static List<String> analyzeData640(String data) {
        List<String> splitList = new ArrayList<>();
        for (int i = 0; i < data.length(); i += 2) {
            if (i + 1 < data.length()) {
                splitList.add(data.substring(i, i + 2));
            } else {
                splitList.add(data.substring(i));
            }
        }
        return splitList;

    }

    public static JSONObject analyze(String code) {
        JSONObject jsonObject = new JSONObject();
        // 起始符
        String start_Symbol = code.substring(0, 4);
        // 业务流水号
        String service_Serial_Number = code.substring(4, 8);
        // 协议版本号
        String protocol_Version_Number = code.substring(8, 12);
        // 时间标签
        String time = code.substring(12, 24);
        // 设备地址
        String address = code.substring(24, 39);
        // 数据长度
        String dataLength1 = code.substring(48, 50);
        // 命令标识
        String Command_Identification = code.substring(52, 54);
        // 数据体
        Integer data_end = hexToInt(dataLength1) * 2 + 54;
        String dataBody = code.substring(54, code.length());
        // 校验码
        String check_Code = code.substring(data_end, data_end + 2);
        // 结束符
        String end = code.substring(data_end + 2, data_end + 6);

        jsonObject.putOnce("code", code);
        jsonObject.putOnce("起始符", start_Symbol);
        jsonObject.putOnce("业务流水号", service_Serial_Number);
        jsonObject.putOnce("协议版本号", protocol_Version_Number);
        jsonObject.putOnce("时间标签", time);
        jsonObject.putOnce("设备地址", address);
        jsonObject.putOnce("数据长度", hexToInt(dataLength1));
        jsonObject.putOnce("命令标识", Command_Identification);
        jsonObject.putOnce("数据体", dataBody);
        jsonObject.putOnce("校验码", check_Code);
        jsonObject.putOnce("结束符", end);

        return jsonObject;
    }

    /**
     * 十进制转ieee754
     */
    public static String getIeee754(String number) {
        //小数取值
        DecimalFormat df = new DecimalFormat("#.0");

        // 十六转十
        Integer integer = hexToInt(number);

        float toFloat = Float.intBitsToFloat(integer);
        if (toFloat == 0) {
            return "0.0";
        }
        return df.format(toFloat);

    }

    /**
     * 将毫秒转化为日期(格式:yyyy-MM-dd hh:mm:ss)
     *
     * @param l
     * @return
     * @throws Exception
     */
    public String contextLoads(Long l) throws Exception {

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        Date date = new Date(l);
        String str1 = sdf1.format(date);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date2 = sdf.parse(str1);
        String str2 = sdf.format(date2);
        return str2;
    }

    /**
     * 格式化数据体
     *
     * @param data 要格式化的字符串
     * @return 将字符串每隔两位为一组，组成集合返回
     */
    public static List<String> formatData(String data) {
        List<String> splitList = new ArrayList<>();
        for (int i = 0; i < data.length(); i += 2) {
            if (i + 1 < data.length()) {
                splitList.add(data.substring(i, i + 2));
            } else {
                splitList.add(data.substring(i));
            }
        }
        return splitList;
    }


    /**
     * @Author YangYu
     * @Description 十六进制转十进制
     * @Date Created in 16:37 2022/1/12
     * @Param [hex]
     */

    public static int hexToInt(String hex) {
        if (hex.length() < 1) {
            return 0;
        } else {
            return Integer.parseInt(hex, 16);
        }
    }

    public static String HexToBin(String hex) {
        Integer num = Integer.parseInt(hex, 16);
        String bin = Integer.toBinaryString(num);
        int length = bin.length();
        if (length == 15) {
            bin = "0" + bin;
        } else if (length == 14) {
            bin = "00" + bin;
        } else if (length == 13) {
            bin = "000" + bin;
        } else if (length == 12) {
            bin = "0000" + bin;
        } else if (length == 11) {
            bin = "00000" + bin;
        } else if (length == 10) {
            bin = "000000" + bin;
        } else if (length == 9) {
            bin = "0000000" + bin;
        } else if (length == 8) {
            bin = "00000000" + bin;
        } else if (length == 7) {
            bin = "000000000" + bin;
        } else if (length == 6) {
            bin = "0000000000" + bin;
        } else if (length == 5) {
            bin = "00000000000" + bin;
        } else if (length == 4) {
            bin = "000000000000" + bin;
        } else if (length == 3) {
            bin = "0000000000000" + bin;
        } else if (length == 2) {
            bin = "00000000000000" + bin;
        }

        return bin;
    }

    private static int negative(String hex) {
        String bits = HexToBin(hex);
        String bit = "0";

        for (int i = 1; i < bits.length(); ++i) {
            if (bits.charAt(i) == '0') {
                bit = bit + "1";
            } else {
                bit = bit + "0";
            }
        }

        String result = addOneToBinaryString(bit);
        int decimal = Integer.parseInt(result, 2);
        return decimal;
    }

    public static String addOneToBinaryString(String binaryStr) {
        char[] binaryChars = binaryStr.toCharArray();
        int n = binaryChars.length;

        int i;
        for (i = n - 1; i >= 0 && binaryChars[i] == '1'; --i) {
        }

        if (i < 0) {
            char[] result = new char[n + 1];
            Arrays.fill(result, '0');
            result[0] = '1';
            return new String(result);
        } else {
            binaryChars[i] = '1';

            for (int j = i + 1; j < n; ++j) {
                binaryChars[j] = '0';
            }

            return new String(binaryChars);
        }
    }
}
